home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 2000 January: Mac OS SDK / Dev.CD Jan 00 SDK2.toast / Development Kits / Hardware / Mac OS USB DDK v1.3f3 / Examples / PrinterClassDriver / PrinterClassDriver.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-08-20  |  122.5 KB  |  3,717 lines  |  [TEXT/MPS ]

  1. /*
  2.     File:        PrinterClassDriver.c
  3.  
  4.     Contains:    MacOS USB printer class driver
  5.                 [ref. IEEE Std 1284-1994]
  6.  
  7.     Version:    xxx put version here xxx
  8.  
  9.  
  10.  
  11.     Copyright:    1998 by Apple Computer, Inc., all rights reserved.
  12.  
  13. */
  14.  
  15.  
  16. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  17.     includes
  18.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  19. #include <Gestalt.h>
  20. #include <Devices.h>
  21. #include <DriverServices.h>
  22. #include <Interrupts.h>
  23. #include <LowMem.h>
  24. #include <Folders.h>
  25. #include <String.h>
  26. #include <stdio.h>
  27. #include <ctype.h>
  28. #include <USB.h>
  29.  
  30. #ifndef __CODEFRAGMENTS__
  31. #include <codefragments.h>
  32. #endif
  33.  
  34. #include "PrinterClassDriver.h"
  35. #include "TradDriverLoaderLib.h"
  36.  
  37. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  38.     constants
  39.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  40. #define MAX_SUFFIX                    127                    // maximum copies we'll enter in unit table
  41. #define kUSBParallelDrvrRsrcID        12
  42. #define kMinDrvrUnitNumber            48                    // minimum unit table entry which we'll install
  43. #define kUSS720MillisecondDelay        3*1000                // poll every three seconds
  44. #define kUSS720StatusMSDelay        100                    // poll ten times per second
  45. #define MAX_USB_TRANSFER_SIZE        TRANSFER_SIZE        // zero acts as manifest for conditional compilation
  46.  
  47. #define kUSBAttributeBulk            0x02
  48. #define kUSBInputEndpointMask        0x80
  49.  
  50. #define kDebugStatusLevel            5
  51. #define kNormalStatusLevel            4
  52.  
  53.  
  54. enum
  55. {
  56.     kUSBv12    =    0x01200000
  57. };
  58.  
  59. enum
  60. {
  61.     kCString = 0,                // StateStr, USBStatusStr selector
  62.     kPString,                    // StateStr, USBStatusStr selector
  63.     kDrvrFirstDigit = 5            // length_byte + ".USB" = 5
  64. };
  65. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  66.     manifest constants
  67. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  68. //
  69. //    DEBUGGING                        extra debugging information to USB Expert Log
  70. //    DOUBLE_BUFFER                    use a page aligned buffer in system heap to double buffer app i/o
  71. //    LOG                                echo all the write data to a log file in the system folder
  72. // LOCK_MEMORY                        LockMemory on the i/o buffer before write and unlock on write completion
  73. // VIRTUAL_MEMORY_CHECK                check the physical addresses of the buffer we pass for write requests
  74. // MACSBUG_ON_READ                    break into MacsBug before each read request
  75. //    MACSBUG_ON_READ_COMPLETE        break into MacsBug at each read completion routine
  76. //    MACSBUG_ON_WRITE                break into MacsBug on each write request
  77. // MACSBUG_ON_WRITE_COMPLETE        break into MacsBug at each write completion routine
  78. //
  79. #define DEBUGGING                        0    /* DEBUGGING */
  80. #define DOUBLE_BUFFER                    1    /* DOUBLE_BUFFER */
  81. #define LOG                                0    /* LOG */
  82. #define LOCK_MEMORY                        1    /* LOCK_MEMORY */
  83. #define MACSBUG_ON_READ                    0    /* MACSBUG_ON_READ */
  84. #define MACSBUG_ON_READ_COMPLETE        0    /* MACSBUG_ON_READ_COMPLETE */ 
  85. #define MACSBUG_ON_WRITE                0    /* MACSBUG_ON_WRITE */
  86. #define MACSBUG_ON_WRITE_COMPLETE        0    /* MACSBUG_ON_WRITE_COMPLETE */ 
  87. #define VIRTUAL_MEMORY_CHECK            0    /* VIRTUAL_MEMORY_CHECK requires LOCK_MEMORY */
  88.  
  89. #if LOG
  90. #define LOGGING(x)    x
  91. #include <stdio.h>
  92. #else
  93. #define LOGGING(x)
  94. #endif
  95.  
  96. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  97.     globals
  98.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  99. static struct usbPrinterPBStruct    printerClassRecord;
  100. static FSSpec                            printerClassDriverFileSpec;
  101. LOGGING( static FILE                    *logfile );
  102.  
  103. SInt16    openRef = 0;        // used to only suspend on last close
  104.  
  105. volatile enum{
  106.     kUSBPrintSuspended,
  107.     kUSBPrintResumed
  108.     }wantToBe = kUSBPrintResumed, currentlyAre = kUSBPrintResumed;
  109.  
  110. // These for resuming reads and writes which were delayed due to resume
  111.  
  112. IOParamPtr Wpb; DCtlPtr Wctl; struct usbPrinterPBStruct *WpPrinterPB;
  113. IOParamPtr Rpb; DCtlPtr Rctl; struct usbPrinterPBStruct *RpPrinterPB;
  114.  
  115. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  116.     prototypes
  117.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  118.  
  119. static void    PrinterDeviceCompletionProc(USBPB *pb);
  120. static void SetNullUSBParamBlock( USBDeviceRef dev, USBPB *pb );
  121. static void    SoftReset( USBPB *usbprint, short interfaceNum );
  122. static void    ClearEndpointHalt( USBPB *usbprint);
  123. static void    CapabilityRequest( USBPB *pb, Ptr p, long length, short config, short interfaceNum, short alternateSetting );
  124. static void    CentronicsStatus( USBPB *usbprint, Ptr p, short interfaceNum );
  125. static void CompletionProc(USBPB *pb);
  126.  
  127. void            PrinterDeviceInitiateTransaction(USBPB *pb);
  128.  
  129. OSErr            CFMInitialization( CFragInitBlock *initBlock );
  130.  
  131. Boolean    gUSBVersionNeedsBulkFixPresent;
  132.  
  133. void        CheckUSBVersion(void);
  134. OSStatus     SecondaryUSBBulkRead(void *pb, void *result);
  135. OSStatus     SecondaryUSBBulkWrite(void *pb, void *result);
  136. OSStatus     SafeUSBBulkRead(USBPB *pb);
  137. OSStatus     SafeUSBBulkWrite(USBPB *pb);
  138.  
  139. void    CheckUSBVersion(void)
  140. {
  141. OSStatus    err;
  142. UInt32        usbVersion;
  143.  
  144.     err = Gestalt('usbv', (long*)&usbVersion);
  145.     if (err == noErr)
  146.         gUSBVersionNeedsBulkFixPresent = (usbVersion < kUSBv12);
  147. }
  148.  
  149. OSStatus SecondaryUSBBulkRead(void *pb, void *result)
  150. {
  151.     *(OSStatus*)result = USBBulkRead((USBPB*)pb);
  152.     return noErr;
  153. }
  154.  
  155. OSStatus SecondaryUSBBulkWrite(void *pb, void *result)
  156. {
  157.     *(OSStatus*)result = USBBulkWrite((USBPB*)pb);
  158.     return noErr;
  159. }
  160.  
  161. OSStatus SafeUSBBulkRead(USBPB *pb)
  162. {
  163.     OSStatus    result;
  164.  
  165.     pb->usbFlags = 0;    // BT we may have set the address request flag
  166.     if (gUSBVersionNeedsBulkFixPresent)
  167.     {
  168.         // Use CallSecondaryInterruptHandler2 to call USBBulkRead if
  169.         // less than USB v1.2 present
  170.         CallSecondaryInterruptHandler2(SecondaryUSBBulkRead, nil, pb, &result);
  171.     }
  172.     else
  173.         result = USBBulkRead(pb);
  174.         
  175.     return result;
  176. }
  177.  
  178. OSStatus SafeUSBBulkWrite(USBPB *pb)
  179. {
  180.     OSStatus    result;
  181.  
  182.     pb->usbFlags = 0;    // BT we may have set the address request flag
  183.     if (gUSBVersionNeedsBulkFixPresent)
  184.     {
  185.         // Use CallSecondaryInterruptHandler2 to call USBBulkWrite if
  186.         // less than USB v1.2 present
  187.         CallSecondaryInterruptHandler2(SecondaryUSBBulkWrite, nil, pb, &result);
  188.     }
  189.     else
  190.         result = USBBulkWrite(pb);
  191.         
  192.     return result;
  193. }
  194.  
  195.  
  196.  
  197.  
  198. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  199.     Name:        HexString8
  200.  
  201.     Input Parameters:    
  202.         v                unsigned long value
  203.         
  204.     Output Parameters:
  205.         p                8 bytes: hex string representing value
  206.         
  207.     Description:
  208.  
  209.  
  210.  
  211. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  212. static void
  213. HexString8( unsigned long v, unsigned char *p )
  214. {
  215.     short    shift;
  216.     
  217.     for ( shift = 32-4; shift >= 0; shift -= 4 )
  218.     {
  219.         char c = (v >> shift) & 0x0F;
  220.         *p++ = c + (c > 9? ('A'-10): '0');
  221.     }
  222. }
  223.  
  224. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  225.     Name:        hexstr
  226.  
  227.     Input Parameters:    
  228.         count                number of bytes
  229.         p                    pointer to bytes
  230.         
  231.     Output Parameters:
  232.         q                    hex dump of data
  233.         
  234.     Description:
  235.  
  236.  
  237.  
  238. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  239. void hexstr( long count, char *p, char *q )
  240. {
  241.     char *s = p;
  242.     long i = count;
  243.     for ( ; count > 0; --count, ++p )
  244.     {
  245.         UInt8 hi, lo;
  246.         hi = (*p >> 4)& 0x0F;
  247.         lo = *p & 0x0F;
  248.         *q++ = '0';
  249.         *q++ = 'x';
  250.         *q++ = hi + (hi > 9? 'A' - 10: '0');
  251.         *q++ = lo + (lo > 9? 'A' - 10: '0');
  252.         *q++ = ' ';
  253.     }
  254.     for ( ; i > 0; --i, ++s )
  255.         *q++ = *s < ' ' || *s > 0x7E? '.': *s;
  256. }
  257.  
  258. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  259.     Name:        ForceUpperStr
  260.  
  261.     Input Parameters:    
  262.         s                    pointer to a null terminated string
  263.         
  264.     Output Parameters:
  265.         s                    string modified by using toupper() on each character.
  266.         
  267.     Description:
  268.  
  269.  
  270.  
  271.  
  272. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  273. void 
  274. ForceUpperStr(char *s)
  275. {
  276.     while(*s){
  277.         *s = toupper(*s);
  278.         s++;
  279.     }
  280. }
  281.     
  282. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  283.     Name:        MakeNameRegistrySafeStr
  284.  
  285.     Input Parameters:    
  286.         s                    pointer to a null terminated string
  287.         
  288.     Output Parameters:
  289.         s                    string modified by replacing / with - on each character.
  290.         
  291.     Description:
  292.  
  293.  
  294.  
  295. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  296. void 
  297. MakeNameRegistrySafeStr(char *s)
  298. {
  299.     while (*s)
  300.     {
  301.         if (*s == '/') 
  302.             *s = '-';
  303.         s++;
  304.     }
  305. }
  306.  
  307.  
  308.  
  309. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  310.     Name:        USBStatusStr
  311.  
  312.     Input Parameters:    
  313.         usbStatus            usb error code
  314.         kind                    kPString or kCString
  315.         
  316.     Output Parameters:
  317.         unsigned char *    description of error (c-string or p-string)
  318.  
  319.     Description:
  320.         a simple mapping of errors to human-readable form
  321.  
  322.  
  323.  
  324.  
  325.  
  326. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  327. static unsigned char *
  328. USBStatusStr( OSStatus usbStatus, short kind )
  329. {
  330.     unsigned char *p;
  331.  
  332.     switch ( usbStatus )
  333.     {
  334.         case    kUSBInternalErr:                    p = kPStrPrinterDriverName"Internal error"; break;
  335.         case    kUSBUnknownDeviceErr:                p = kPStrPrinterDriverName"Unknown device"; break;
  336.         case    kUSBUnknownPipeErr:                 p = kPStrPrinterDriverName"Unknown pipe"; break;
  337.         case    kUSBTooManyPipesErr:                p = kPStrPrinterDriverName"Too many pipes"; break;
  338.         case    kUSBIncorrectTypeErr:                p = kPStrPrinterDriverName"Incorrect type"; break;
  339.         case    kUSBRqErr:                            p = kPStrPrinterDriverName"Request error"; break;
  340.         case    kUSBUnknownRequestErr:                p = kPStrPrinterDriverName"Unknown request"; break;
  341.         case    kUSBTooManyTransactionsErr:            p = kPStrPrinterDriverName"Too many transactions"; break;
  342.         case    kUSBAlreadyOpenErr:                    p = kPStrPrinterDriverName"Already open"; break;
  343.         case    kUSBNoDeviceErr:                    p = kPStrPrinterDriverName"No device"; break;
  344.         case    kUSBDeviceErr:                        p = kPStrPrinterDriverName"Device error"; break;
  345.         case    kUSBOutOfMemoryErr:                    p = kPStrPrinterDriverName"Out of memory"; break;
  346.         case    kUSBNotFound:                        p = kPStrPrinterDriverName"Not found"; break;
  347.         case    kUSBPBVersionError:                    p = kPStrPrinterDriverName"Wrong pbVersion"; break;
  348.         case    kUSBPBLengthError:                    p = kPStrPrinterDriverName"pbLength too small"; break;
  349.         case    kUSBCompletionError:                p = kPStrPrinterDriverName"Missing completion routine"; break;
  350.         case    kUSBFlagsError:                        p = kPStrPrinterDriverName"Unused flags not zeroed"; break;
  351.         case    kUSBAbortedError:                    p = kPStrPrinterDriverName"Pipe aborted"; break;
  352.         case    kUSBNoBandwidthError:                p = kPStrPrinterDriverName"No bandwidth available"; break;
  353.         case    kUSBPipeIdleError:                    p = kPStrPrinterDriverName"Pipe is idle"; break;
  354.         case    kUSBPipeStalledError:                p = kPStrPrinterDriverName"Pipe is stalled"; break;
  355.         case    kUSBUnknownInterfaceErr:            p = kPStrPrinterDriverName"Unknown interfaceRef"; break;
  356.         case    kUSBDeviceBusy:                        p = kPStrPrinterDriverName"Device is busy"; break;
  357.         case    kUSBDevicePowerProblem:                p = kPStrPrinterDriverName"Device power problem"; break;
  358.         case    kUSBInvalidBuffer:                    p = kPStrPrinterDriverName"Bad buffer (nil?)"; break;
  359.         case    kUSBDeviceSuspended:                p = kPStrPrinterDriverName"Device is suspended"; break;
  360.         case    kUSBDeviceNotSuspended:                p = kPStrPrinterDriverName"Device is not suspended"; break;
  361.         case    kUSBDeviceDisconnected:                p = kPStrPrinterDriverName"Disconnected during suspend/reset"; break;
  362.         case    kUSBTimedOut:                        p = kPStrPrinterDriverName"Transaction timed out"; break;
  363.  
  364.         case    kUSBLinkErr:                        p = kPStrPrinterDriverName"Link Err"; break;
  365.         case    kUSBCRCErr:                            p = kPStrPrinterDriverName"Comms/Device err, bad CRC";  break;        
  366.         case    kUSBBitstufErr:                        p = kPStrPrinterDriverName"Comms/Device err, bitstuffing"; break;        
  367.         case    kUSBDataToggleErr:                    p = kPStrPrinterDriverName"Comms/Device err, Bad data toggle"; break;        
  368.         case    kUSBEndpointStallErr:                p = kPStrPrinterDriverName"Device didn't understand"; break;        
  369.         case    kUSBNotRespondingErr:                p = kPStrPrinterDriverName"No device, device hung"; break;        
  370.         case    kUSBPIDCheckErr:                    p = kPStrPrinterDriverName"Comms/Device err, PID CRC error"; break;        
  371.         case    kUSBWrongPIDErr:                    p = kPStrPrinterDriverName"Comms/Device err, Bad or wrong PID"; break;        
  372.         case    kUSBOverRunErr:                        p = kPStrPrinterDriverName"Packet too large or more data than buffer"; break;        
  373.         case    kUSBUnderRunErr:                    p = kPStrPrinterDriverName"Less data than buffer"; break;        
  374.         case    kUSBRes1Err:                        p = kPStrPrinterDriverName"kUSBRes1Err"; break;        
  375.         case    kUSBRes2Err:                        p = kPStrPrinterDriverName"kUSBRes1Err"; break;        
  376.         case    kUSBBufOvrRunErr:                    p = kPStrPrinterDriverName"Buffer over run error"; break;        
  377.         case    kUSBBufUnderRunErr:                    p = kPStrPrinterDriverName"Buffer under run error"; break;        
  378.         case    kUSBNotSent1Err:                    p = kPStrPrinterDriverName"Transaction not sent1"; break;        
  379.         case    kUSBNotSent2Err:                    p = kPStrPrinterDriverName"Transaction not sent2"; break;    
  380.         default:
  381.             p = kPStrPrinterDriverName"Unknown error nnnnnnnn";
  382.             HexString8( usbStatus, p + *p - 8 + 1 );
  383.             break;
  384.     }
  385.     
  386.     return kind == kPString? p: p + 1;
  387. }
  388.  
  389. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  390.     Name:        StateStr
  391.  
  392.     Input Parameters:    
  393.         usbRefCon            usb error code
  394.         kind                    kPString or kCString
  395.         
  396.     Output Parameters:
  397.         unsigned char *    description of state (c-string or p-string)
  398.  
  399.     Description:
  400.         a simple mapping of states to human-readable form
  401.  
  402.  
  403.  
  404.  
  405.  
  406. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  407. static unsigned char *
  408. StateStr( OSStatus refCon, short kind )
  409. {
  410.     unsigned char *p;
  411.  
  412.     refCon &= ~(kTransactionPending | kRetryTransaction | kReturnFromDriver);
  413.     switch ( refCon )
  414.     {
  415.         case kUndefined:                            p = kPStrPrinterDriverName"kUndefined"; break;
  416.         case kNilCompletion:                        p = kPStrPrinterDriverName"kNilCompletion"; break;
  417.  
  418.         case kFindInterface_bidirectional:            p = kPStrPrinterDriverName"kFindInterface_bidirectional"; break;
  419.         case kFindInterface_unidirectional:            p = kPStrPrinterDriverName"kFindInterface_unidirectional"; break;
  420.         case kOpenDevice:                            p = kPStrPrinterDriverName"kOpenDevice"; break;
  421.         case kNewInterfaceRef:                        p = kPStrPrinterDriverName"kNewInterfaceRef"; break;
  422.  
  423.         case kSetInterface:                            p = kPStrPrinterDriverName"kSetInterface"; break;
  424.         case kConfigureInterface:                    p = kPStrPrinterDriverName"kConfigureInterface"; break;
  425.         case kGetCapabilityString:                    p = kPStrPrinterDriverName"kGetCapabilityString"; break;
  426.         case kDelayGetCapability:                    p = kPStrPrinterDriverName"kDelayGetCapability"; break;
  427.  
  428.         case kAllocateCapabilityMem:                p = kPStrPrinterDriverName"kAllocateCapabilityMem"; break;
  429.         case kGetFullCapabilityString:                p = kPStrPrinterDriverName"kGetFullCapabilityString"; break;
  430.         case kGetInterface:                            p = kPStrPrinterDriverName"kGetInterface"; break;
  431.         case kFindBulkOutPipe:                        p = kPStrPrinterDriverName"kFindBulkOutPipe"; break;
  432.  
  433.         case kFindBulkInPipe:                        p = kPStrPrinterDriverName"kFindBulkInPipe"; break;
  434.         case kTaskTimeRequired:                        p = kPStrPrinterDriverName"kTaskTimeRequired"; break;
  435.  
  436.         case kGetCentronicsStatus:                    p = kPStrPrinterDriverName"kGetCentronicsStatus"; break;
  437.         case kDelayGetCentronicsStatus:                p = kPStrPrinterDriverName"kDelayGetCentronicsStatus"; break;
  438.  
  439.         case kDeallocateCapbilityString:            p = kPStrPrinterDriverName"kDeallocateCapbilityString"; break;
  440.         default:
  441.             p = kPStrPrinterDriverName"Unknown state nnnnnnnn";
  442.             HexString8( refCon, p + *p - 8 + 1 );
  443.             break;
  444.     }
  445.     return kind == kPString? p: p + 1;    
  446. }
  447.  
  448. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  449.     Name:        HiHex
  450.  
  451.     Input Parameters:    
  452.         v                        only low byte used
  453.         
  454.     Output Parameters:
  455.         <function result>    high nibble represented as ASCII char
  456.         
  457.     Description:
  458.  
  459.  
  460.  
  461. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  462. static unsigned char
  463. HiHex( unsigned char v )
  464. {
  465.     unsigned char    hinibble = (v >> 4) & 0x0f;
  466.     return hinibble + ((hinibble > 9)? ('A'-10): '0');
  467. }
  468.  
  469. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  470.     Name:        LoHex
  471.  
  472.     Input Parameters:    
  473.         v                        only low byte used
  474.         
  475.     Output Parameters:
  476.         <function result>    low nibble represented as ASCII char
  477.         
  478.     Description:
  479.  
  480.  
  481.  
  482. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  483. static unsigned char
  484. LoHex( unsigned char v )
  485. {
  486.     unsigned char    lonibble = v & 0x0f;
  487.     return lonibble + ((lonibble > 9)? ('A'-10): '0');
  488. }
  489.  
  490. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  491.     Name:        immediateError
  492.  
  493.     Input Parameters:    
  494.         
  495.     Output Parameters:
  496.         
  497.     Description:
  498.  
  499.  
  500.  
  501. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  502. static Boolean
  503. immediateError(OSStatus err)
  504. {
  505.     return((err != kUSBPending) && (err != noErr) );
  506. }
  507.  
  508. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  509.     Name:        SetNullUSBParamBlock
  510.  
  511.     Input Parameters:    
  512.         pb                    pointer to USB parameter block
  513.         dev                USB device reference
  514.     Output Parameters:
  515.         pb                    all fields set to default values
  516.  
  517.     Description:
  518.         setup a USB parameter block for use by the current device
  519.  
  520.  
  521.  
  522.  
  523. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  524. static void
  525. SetNullUSBParamBlock( USBDeviceRef dev, USBPB *pb )
  526. {
  527.     pb->qlink = NULL;
  528.     pb->qType = 0;
  529.     pb->pbLength = sizeof(USBPB);
  530.     pb->pbVersion = kUSBCurrentPBVersion;
  531.     pb->usbFlags = 0;
  532.     pb->usbStatus = noErr;
  533.     pb->usbCompletion = (USBCompletion) NULL;
  534.  
  535.     pb->usbReference = dev;
  536. }
  537.  
  538. // BT - 15Jun99, Callback for the suspend call.
  539. static void usbPrintResume(USBPB *pb)
  540. {
  541. IOParamPtr resumePB;
  542. DCtlPtr resumeCtl;
  543. struct usbPrinterPBStruct *resumePrinterPB;
  544.  
  545.     if(pb->usbStatus != noErr)
  546.     {
  547.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB print driver USBPrintDoSuspendResume error", pb->usbStatus);
  548.     }
  549.     else
  550.     {
  551.         currentlyAre = kUSBPrintResumed;
  552.         if(Wpb != nil)
  553.         {
  554.             // We have to restart a waiting write
  555.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB print driver resumeing write", 0);
  556.             resumeCtl = Wctl;
  557.             resumePrinterPB = WpPrinterPB;
  558.             resumePB = Wpb;
  559.             Wpb = nil;
  560.             QueueWrite(resumePB, resumeCtl, resumePrinterPB);
  561.         }
  562.     
  563.         if(Rpb != nil)
  564.         {
  565.             // We have to restart a waiting write
  566.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB print driver resumeing read", 0);
  567.             resumeCtl = Rctl;
  568.             resumePrinterPB = RpPrinterPB;
  569.             resumePB = Rpb;
  570.             Rpb = nil;
  571.             QueueRead(resumePB, resumeCtl, resumePrinterPB);
  572.         }
  573.     }
  574.     pb->usbRefcon = 0;
  575. }
  576.  
  577. // BT - 15Jun99, work out if we need to and can suspend or resume and do it.
  578. static USBPrintDoSuspendResume(USBDeviceRef ref)
  579. {
  580. static USBPB pb;
  581. OSStatus err = noErr;
  582.     if(wantToBe != currentlyAre)
  583.     {
  584.         if(currentlyAre == kUSBPrintSuspended)
  585.         {
  586.             USBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver resuming device", ref);
  587.             err = USBResumeDeviceByReference(ref);
  588.         }
  589.         else if(wantToBe == kUSBPrintSuspended)
  590.         {
  591.             if( (printerClassRecord.pb.usbCompletion != nil) || 
  592.                 (printerClassRecord.in.usbCompletion != nil) || 
  593.                 (printerClassRecord.out.usbCompletion != nil) )
  594.             {
  595.                 USBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver can't suspend, busy", (UInt32) printerClassRecord.pb.usbCompletion);
  596.                 return(noErr);
  597.             }
  598.         
  599.             if(pb.usbRefcon != 0)
  600.             {
  601.                 USBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver suspend already in process", err);
  602.                 return(noErr);
  603.             }
  604.             USBExpertStatusLevel(kDebugStatusLevel, ref, "\pUSB print driver suspending device", ref);
  605.             SetNullUSBParamBlock(ref, &pb);
  606.             pb.usbCompletion = usbPrintResume;
  607.             pb.usbRefcon = 1;
  608.             currentlyAre = kUSBPrintSuspended;
  609.             err = USBSuspendDevice(&pb);
  610.         }
  611.         if( (err != kUSBPending) && (err != noErr) )
  612.         {
  613.             USBExpertStatusLevel(2, ref, "\pUSB print driver USBPrintDoSuspendResume error", err);
  614.         }
  615.     }
  616.     return(noErr);
  617. }
  618.  
  619.  
  620.  
  621.  
  622.  
  623. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  624.     Name:        ParseCapability
  625.  
  626.     Input Parameters:    
  627.         capability            pointer to 1284-1994 capability string
  628.         attribute            pointer to c-string key we're retrieving (terminate with colon)
  629.         *result_length        maximum length of the result 
  630.         
  631.     Output Parameters:
  632.         result                c-string which followed the key and was terminated by semi-colon
  633.                                 (semi-colon has been stripped)
  634.         *result_length        actual length of the result (may be zero)
  635.     
  636.     Description:
  637.         Search for "attribute" in the 1284 "capability" string
  638.         The identifier is terminated with a semi-colon
  639.  
  640.         Return the attribute in result
  641.             null-string if attribute not found.
  642.  
  643.  
  644.  
  645.  
  646. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  647. static void
  648. ParseCapability(
  649.     unsigned char    *capability,
  650.     unsigned char    *attribute,
  651.     unsigned char    *result,
  652.     short            *result_length 
  653. )
  654. {
  655.     //
  656.     //    search for "attribute" in the 1284 "capability" string
  657.     //
  658.     //    the identifier is terminated with a semi-colon
  659.     //
  660.     //    return the attribute in result
  661.     //            null-string if attribute not found
  662.     //
  663.     //    <to do> skip blanks, isolate colon, skip blanks
  664.     //
  665.     UInt32                source_length;
  666.     UInt16                target_length;
  667.     unsigned char        *source,
  668.                         *target,
  669.                         *destination;
  670.     //
  671.     //    begin a brute force search
  672.     //
  673.     source = attribute;
  674.     source_length = CStrLen((char *)attribute );
  675.  
  676.     target = capability + 2;    // skip the length
  677.     target_length =  *(UInt16*)capability;
  678.     if (target_length >= 2)
  679.         target_length -= 2;            // don't count the length
  680.     else
  681.         target_length = 0;
  682.         
  683.     while ( target_length >= source_length )
  684.     {
  685.         if ( memcmp( source, target, source_length ) == 0 )
  686.             break;
  687.         --target_length;
  688.         ++target;
  689.     }
  690.  
  691.     *result = '\0';    // empty result
  692.     destination = result;
  693.  
  694.     target += source_length;
  695.     target_length -= source_length;    // skip the attribute string
  696.  
  697.     if ( target_length > 0 )
  698.     {
  699.         //
  700.         //    we found the attribute in the capability string
  701.         //
  702.         while ( destination - result < *result_length )    // arbitrarily limit reply
  703.         {
  704.             if ( *target == ';' || target_length == 0)
  705.                 break;
  706.             *destination++ = *target++;        // copy a byte of attribute over
  707.             --target_length;
  708.         }
  709.         *destination++ = '\0';                        // trailing NUL
  710.         *result_length = destination - result;    // report the length of the data (with trailing NUL)
  711.     }
  712. }
  713.  
  714.  
  715. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  716.     Name:        GetClass
  717.  
  718.     Input Parameters:    
  719.         capability            pointer to 1284-1994 capability string
  720.         *result_length        maximum length of the result 
  721.         
  722.     Output Parameters:
  723.         result                c-string extracted from the MODEL key
  724.         *result_length        actual length of the result  (may be zero)
  725.         
  726.     Description:
  727.         CLASS is a Microsoft extension to the 1284-capability string
  728.         if we don't find it
  729.             we assume that the device is a printer
  730.         Since the USB hardware has already indicated this, we're really allowing
  731.         devices which aren't printers to be reached via the DRVRs we've installed.
  732.  
  733.  
  734.  
  735.  
  736. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  737. static void
  738. GetClass(
  739.     unsigned char    *capability,
  740.     unsigned char    *result,
  741.     short            *result_length
  742. )
  743. {
  744.     //
  745.     //    We supply the upper-case PRINTER to be consistent with 1284-1994
  746.     //        if we don't find a class.
  747.     //
  748.     ParseCapability( capability, (unsigned char *) "CLASS:", result, result_length);
  749.     if ( *result == '\0' )
  750.         ParseCapability( capability, (unsigned char *) "CLS:", result, result_length);
  751.     if ( *result == '\0' )
  752.         CStrCopy( (char *)result, "PRINTER" );
  753. }
  754.  
  755.  
  756. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  757.     Name:        GetModel
  758.  
  759.     Input Parameters:    
  760.         capability            pointer to 1284-1994 capability string
  761.         *result_length        maximum length of the result 
  762.         
  763.     Output Parameters:
  764.         result                c-string extracted from the MODEL key
  765.         *result_length        actual length of the result  (may be zero)
  766.             
  767.     Description:
  768.         MODEL is a required field of the 1284-capability string
  769.         MODEL may be abbreviated MDL
  770.  
  771.  
  772.  
  773.  
  774. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  775. static void
  776. GetModel(
  777.     unsigned char    *capability, 
  778.     unsigned char    *result,
  779.     short            *result_length
  780. )
  781. {
  782.     //
  783.     //    Most manufacturers abbreviate, so we search for MDL first
  784.     //
  785.     ParseCapability( capability, (unsigned char *) "MDL:", result, result_length );
  786.     if ( *result == '\0' )
  787.         ParseCapability( capability, (unsigned char *) "MODEL:", result, result_length );
  788. }
  789.  
  790.  
  791. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  792.     Name:        GetCommandSet
  793.  
  794.     Input Parameters:    
  795.         
  796.     Output Parameters:
  797.         
  798.     Description:
  799.  
  800.  
  801.  
  802.  
  803. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  804. static void
  805. GetCommandSet(
  806.     unsigned char    *capability, 
  807.     unsigned char    *result,
  808.     short              *result_length
  809. )
  810. {
  811.     //
  812.     //    COMMAND-SET is a required field of the 1284-capability string
  813.     //    COMMAND-SET may be abbreviated CMD
  814.     //
  815.     ParseCapability( capability, (unsigned char *) "CMD:", result, result_length );
  816.     if ( *result == '\0' )
  817.         ParseCapability( capability, (unsigned char *) "COMMAND SET:", result, result_length );
  818. }
  819.  
  820. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  821.     Name:        GetManufacturer
  822.  
  823.     Input Parameters:    
  824.         
  825.     Output Parameters:
  826.         
  827.     Description:
  828.  
  829.  
  830.  
  831. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  832. static void
  833. GetManufacturer(
  834.     unsigned char *capability, 
  835.     unsigned char *result,
  836.     short *result_length
  837. )
  838. {
  839.     //
  840.     //    MANUFACTURER is a required field of the 1284-capability string
  841.     //    MANUFACTURER may be abbreviated MFG
  842.     //
  843.     ParseCapability( capability, (unsigned char *) "MFG:", result, result_length );
  844.     if ( *result == '\0' )
  845.         ParseCapability( capability, (unsigned char *) "MANUFACTURER:", result, result_length );
  846.     if ( *result == '\0' )
  847.         ParseCapability( capability, (unsigned char *) "HMFG:", result, result_length );
  848. }
  849.  
  850.  
  851. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  852.     Name:        DeregisterDevice
  853.  
  854.     Input Parameters:    
  855.         pPrinterPB
  856.  
  857.     Output Parameters:
  858.         <none>
  859.         
  860.     Description:
  861.         remove the device from the name registry
  862.  
  863.  
  864.  
  865.  
  866. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  867. #define kMinNameLength    27
  868. #define kMinModelLength    25
  869. #define kMinClassLength    23
  870.  
  871. static OSStatus
  872. DeregisterDevice( struct usbPrinterPBStruct *pPrinterPB )
  873. {
  874. RegEntryID            self, child, parent;
  875. RegEntryIter         cookie;
  876.  
  877. OSStatus    err = noErr;
  878. Str255        tempStr1,tempStr2;
  879. UInt32        nameLength, modelLength,devclassLength;
  880. Boolean     done = false;
  881.  
  882.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Removing the printer from the name registry", 0 );
  883.     // delete the printer node
  884.     // print out the printer's name (which is the same as the node name)
  885.     nameLength = CStrLen((char *)pPrinterPB->name);
  886.     CStrCopy((char *)tempStr1, (char *)(kCStrPrinterDriverName"Printer name:  "));
  887.     CStrCat((char *)tempStr1, (char *)pPrinterPB->name);
  888.     CStrToPStr((unsigned char *)tempStr2, (char *)tempStr1 );
  889.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempStr2, nameLength );
  890.     
  891.     // locate the model node (parent of printer), and delete it if the printer has no siblings
  892.     if (nameLength<kMinNameLength)
  893.     {
  894.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Warning!! Printer name string is not long enough!", nameLength);
  895.     }
  896.     else
  897.     {
  898.         RegistryEntryIDInit( &self );
  899.         err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->name , &self );
  900.         if ( err == noErr )
  901.         {    
  902.             err = RegistryEntryDelete( &self);
  903.         }
  904.         else
  905.         {
  906.             USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Printer node not found!", err );
  907.         }
  908.         RegistryEntryIDDispose(&self);
  909.         
  910.         if (err == noErr &&  pPrinterPB->outRefNum != -1 )
  911.             err = TradRemoveDriver( pPrinterPB->outRefNum, false );
  912.         if (err == noErr &&  pPrinterPB->inRefNum != -1 )
  913.             err = TradRemoveDriver( pPrinterPB->inRefNum, false );
  914.     }
  915.  
  916.  
  917.     // print out the printer's model (which is the same as the node's parent)
  918.     modelLength = CStrLen((char *)pPrinterPB->model);
  919.     CStrCopy((char *)tempStr1, (char *)(kCStrPrinterDriverName"Printer model: "));
  920.     CStrCat((char *)tempStr1, (char *)pPrinterPB->model);
  921.     CStrToPStr((unsigned char *)tempStr2, (char *)tempStr1 );
  922.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempStr2, modelLength );
  923.     
  924.  
  925.     // locate the model node (parent of printer), and delete it if the printer has no siblings
  926.     if (modelLength<kMinModelLength)
  927.     {
  928.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Warning!! Printer model string is not long enough!", modelLength);
  929.     }
  930.     else
  931.     {
  932.         RegistryEntryIDInit( &parent );
  933.         err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->model , &parent );
  934.         if ( err == noErr )
  935.         {    
  936.             RegistryEntryIDInit(&child);
  937.             
  938.             err = RegistryEntryIterateCreate(&cookie);
  939.             if (err == noErr)
  940.                 err = RegistryEntryIterateSet(&cookie, &parent);
  941.             if (err == noErr)
  942.                 err = RegistryEntryIterate(&cookie, kRegIterChildren, &child, &done);
  943.             if ((err == noErr) && done)
  944.             {
  945.                 USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"No siblings detected, so delete the parent of printer", 0 );
  946.                 err = RegistryEntryDelete(&parent);
  947.             }
  948.             else
  949.             {
  950.                 USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Siblings (or error) detected.  Leaving parent in place", err );
  951.             }
  952.             RegistryEntryIterateDispose(&cookie);
  953.         }
  954.         else
  955.         {
  956.             USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Parent node not found!", err );
  957.         }
  958.         RegistryEntryIDDispose(&parent);
  959.     }
  960.     
  961.     // print out the printer's model (which is the same as the node's parent)
  962.     devclassLength = CStrLen((char *)pPrinterPB->devclass);
  963.     CStrCopy((char *)tempStr1, (char *)(kCStrPrinterDriverName"Printer class: "));
  964.     CStrCat((char *)tempStr1, (char *)pPrinterPB->devclass);
  965.     CStrToPStr((unsigned char *)tempStr2, (char *)tempStr1 );
  966.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempStr2, devclassLength );
  967.     
  968.  
  969.     // locate the class node (parent of model), and delete it if the class has no siblings
  970.     if (devclassLength<kMinClassLength)
  971.     {
  972.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Warning!! Printer class string not long enough!", devclassLength);
  973.     }
  974.     else
  975.     {
  976.         RegistryEntryIDInit( &parent );
  977.         err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->devclass , &parent );
  978.         if ( err == noErr )
  979.         {    
  980.             RegistryEntryIDInit(&child);
  981.             
  982.             err = RegistryEntryIterateCreate(&cookie);
  983.             if (err == noErr)
  984.                 err = RegistryEntryIterateSet(&cookie, &parent);
  985.             if (err == noErr)
  986.                 err = RegistryEntryIterate(&cookie, kRegIterChildren, &child, &done);
  987.             if ((err == noErr) && done)
  988.             {
  989.                 USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"No models found, so delete the class node", 0 );
  990.                 err = RegistryEntryDelete(&parent);
  991.             }
  992.             else
  993.             {
  994.                 USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Models detected.  Leaving class nodes in place", err );
  995.             }
  996.             RegistryEntryIterateDispose(&cookie);
  997.         }
  998.         else
  999.         {
  1000.             USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Parent node not found!", err );
  1001.         }
  1002.         RegistryEntryIDDispose(&parent);
  1003.     }
  1004.     
  1005.     return err;
  1006. }
  1007.  
  1008. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1009.     Name:        RegisterDevice
  1010.  
  1011.     Input Parameters:    
  1012.         pPrinterPB
  1013.  
  1014.     Output Parameters:
  1015.         <none>
  1016.         
  1017.     Description:
  1018.         add the device into the name registry; we can't insert just the node
  1019.         if the parent nodes aren't present.
  1020.  
  1021.         if it isn't present
  1022.             insert the device CLASS into the registry
  1023.         if it isn't present
  1024.             insert the device MODEL into the registry
  1025.         finally insert the device itself into the registry
  1026.             we're careful to rename multiple devices
  1027.  
  1028.  
  1029.  
  1030.  
  1031.  
  1032.  
  1033.  
  1034.  
  1035.  
  1036. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1037. static OSStatus
  1038. RegisterDevice( struct usbPrinterPBStruct *pPrinterPB )
  1039. {
  1040.     //
  1041.     //    add the device into the name registry
  1042.     //    if it isn't present
  1043.     //        insert the device CLASS into the registry
  1044.     //    if it isn't present
  1045.     //        insert the device MODEL into the registry
  1046.     //    finally insert the device itself into the registry
  1047.     //        we're careful to rename multiple devices
  1048.     //
  1049. Str255        identification,
  1050.                 devclass,
  1051.                 model,
  1052.                 nameregmodel,
  1053.                 commands,
  1054.                 tempstr;
  1055.                 
  1056. RegEntryID    parent, where, self;
  1057.  
  1058. OSStatus        err;
  1059.  
  1060. short            model_length,
  1061.                 command_length,
  1062.                 class_length;
  1063.  
  1064.  
  1065.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Adding the printer to the name registry", 0 );
  1066.     CStrCopy((char *)pPrinterPB->devclass, "");
  1067.     CStrCopy((char *)pPrinterPB->model, "");
  1068.     CStrCopy((char *)pPrinterPB->name, "");
  1069.  
  1070.     command_length = sizeof(commands);
  1071.     GetCommandSet(pPrinterPB->pCapabilityString, commands, &command_length );
  1072.  
  1073.  
  1074.     // get device class and add it to the name registry.  Typically PRINTER or Printer
  1075.     class_length = sizeof(devclass);
  1076.     GetClass( pPrinterPB->pCapabilityString, devclass, &class_length );
  1077.     // force the device class to all uppercase.
  1078.     ForceUpperStr((char *)devclass);
  1079.     
  1080.     CStrCopy( (char *)pPrinterPB->devclass, (char *)"Devices:device-tree:" );
  1081.     CStrCat( (char *)pPrinterPB->devclass, (char *)devclass );
  1082.     
  1083.     RegistryEntryIDInit( &where );
  1084.     err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->devclass, &where );
  1085.     if ( err == nrPathNotFound ) 
  1086.     {
  1087.         //    class not in registry
  1088.         //        create a node for all devices of this CLASS
  1089.         //
  1090.         RegistryEntryIDInit( &parent );
  1091.         err = RegistryCStrEntryLookup( nil, "Devices:device-tree:" , &parent );
  1092.         if ( err == noErr )
  1093.             err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->devclass, &where );
  1094.         RegistryEntryIDDispose(&parent);
  1095.  
  1096.     }
  1097.     
  1098.     CStrToPStr(tempstr, (char *)pPrinterPB->devclass);
  1099.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempstr, 0 );
  1100.     
  1101.     //
  1102.     //    add this model into the name registry of this class
  1103.     //
  1104.     if ( err == noErr )
  1105.     {
  1106.         model_length = sizeof(model);
  1107.         GetModel( pPrinterPB->pCapabilityString, model, &model_length );
  1108.         CStrCopy( (char *)nameregmodel, (char *)model);
  1109.         MakeNameRegistrySafeStr((char *)nameregmodel);
  1110.         if ( *model != '\0' )
  1111.         {
  1112.             CStrCopy( (char *)pPrinterPB->model, "Devices:device-tree:" );
  1113.             CStrCat( (char *)pPrinterPB->model, (char *)devclass );
  1114.             CStrCat( (char *)pPrinterPB->model, ":" );
  1115.             if ( *model == '\0'  )
  1116.             {
  1117.                 CStrCat( (char *)pPrinterPB->model, (char *)"USB_PRINTERCLASS" );
  1118.             }
  1119.             else
  1120.             {
  1121.                 CStrCat( (char *)pPrinterPB->model, (char *)nameregmodel );
  1122.             }
  1123.             RegistryEntryIDInit( &self );
  1124.             err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->model , &self );
  1125.             if ( err != noErr )
  1126.             {
  1127.                 // model not in registry
  1128.                 err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->model, &self );
  1129.             }
  1130.             
  1131.             RegistryEntryIDDispose(&self);
  1132.         }
  1133.         CStrToPStr(tempstr, (char *)pPrinterPB->model);
  1134.         USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempstr, 0 );
  1135.     }
  1136.     
  1137.     //
  1138.     //    add this instance of this model of this class
  1139.     //        into the name registry
  1140.     //
  1141.     if ( *model == '\0'  )
  1142.     {
  1143.         //
  1144.         //    possibly the cable isn't firmly connected or the printer isn't switched on
  1145.         //
  1146.         err = kUSBInternalErr;
  1147.         USBExpertFatalError(pPrinterPB->deviceRef, err, kPStrPrinterDriverName"Model undefined", 0);
  1148.     }
  1149.     if ( err == noErr )
  1150.     {
  1151.         //
  1152.         //    start off by identifying the device simply by the model name
  1153.         //        increment the numeric suffix until we successfully registry the device
  1154.         //
  1155.         Str32    suffix;
  1156.         short    numeric_suffix;
  1157.  
  1158.         CStrCopy( (char *)identification, (char *)nameregmodel );
  1159.         RegistryEntryIDInit( &self );
  1160.         for ( numeric_suffix = 1; numeric_suffix < MAX_SUFFIX; ++numeric_suffix )
  1161.         {
  1162.             CStrCopy( (char *)pPrinterPB->name, "Devices:device-tree:" );
  1163.             CStrCat( (char *)pPrinterPB->name, (char *)devclass );
  1164.             CStrCat( (char *)pPrinterPB->name, ":" );
  1165.             CStrCat( (char *)pPrinterPB->name, (char *)nameregmodel );
  1166.             CStrCat( (char *)pPrinterPB->name, ":" );
  1167.             CStrCat( (char *)pPrinterPB->name, (char *)identification );
  1168.             err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->name , &self );
  1169.             if ( err != noErr )
  1170.             {
  1171.                 // enter device in registry
  1172.                 err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->name, &self );
  1173.                 if ( err == noErr )
  1174.                 {
  1175.                     CStrCopy( (char *)identification, (char *)model );
  1176.                     if (numeric_suffix > 1)
  1177.                     {
  1178.                         sprintf( (char *)suffix, " %d", numeric_suffix-1 );
  1179.                         CStrCat( (char *)identification, (char *)suffix );
  1180.                     }
  1181.                     err = RegistryPropertyCreate( &self, "modelName", identification, strlen((char *)identification) );
  1182.                 }
  1183.                 if ( err == noErr )
  1184.                     err = RegistryPropertyCreate( &self, "drvrOut", &pPrinterPB->driverOutName, 1 + pPrinterPB->driverOutName[0] );
  1185.                 if ( err == noErr )
  1186.                     err = RegistryPropertyCreate( &self, "outRef", &pPrinterPB->outRefNum, sizeof(pPrinterPB->outRefNum) );
  1187.                 
  1188.                 if (pPrinterPB->printerProtocol != kUSBPrinterUnidirectionalProtocol)
  1189.                 {
  1190.                     if ( err == noErr )
  1191.                         err = RegistryPropertyCreate( &self, "drvrIn", &pPrinterPB->driverInName, 1 + pPrinterPB->driverInName[0] );
  1192.                     if ( err == noErr )
  1193.                         err = RegistryPropertyCreate( &self, "inRef", &pPrinterPB->inRefNum, sizeof(pPrinterPB->inRefNum) );
  1194.                 }
  1195.                 if ( err == noErr )
  1196.                     err = RegistryPropertyCreate( &self, "privateData", &pPrinterPB, sizeof(pPrinterPB) );
  1197.                 if ( err == noErr )
  1198.                     err = RegistryPropertyCreate( &self, "read", &pPrinterPB->r, sizeof(QueueUSBReadUPP) );
  1199.                 if ( err == noErr )
  1200.                     err = RegistryPropertyCreate( &self, "write", &pPrinterPB->w, sizeof(QueueUSBWriteUPP) );
  1201.                 if ( err == noErr && *commands != '\0' )
  1202.                     err = RegistryPropertyCreate( &self, "command-set", &commands, command_length );
  1203.                 break;
  1204.             }
  1205.             //
  1206.             //    if this name didn't succeed
  1207.             //        try the next numeric suffix
  1208.             //
  1209.             sprintf( (char *)suffix, " %d", numeric_suffix );
  1210.             CStrCopy( (char *)identification, (char *)nameregmodel );
  1211.             CStrCat( (char *)identification, (char *)suffix );
  1212.         }
  1213.         RegistryEntryIDDispose(&self);
  1214.     }
  1215.     pPrinterPB->printerRegistered = true;
  1216.     
  1217.     CStrToPStr((unsigned char *)tempstr, (char const *)pPrinterPB->name );
  1218.     
  1219.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Added printer to name registry", 0 );
  1220.     USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, tempstr, err );
  1221.     RegistryEntryIDDispose(&where);
  1222.  
  1223.     LOGGING( logfile = fopen( "USBPrinter.log", "wb+" ) );
  1224.     return err;
  1225. }
  1226.  
  1227. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1228.     Name:        LoadResources
  1229.  
  1230.     Input Parameters:
  1231.         pPrinterPB            pointer to class driver's private storage
  1232.         
  1233.     Output Parameters:
  1234.         OSStatus                resource load error
  1235.         
  1236.     Description:
  1237.         Initialize time is the only safe time to to load resources from our file.
  1238.         Here's where we load resources and detach them from the resource manager.
  1239.         Later we'll use these private copies instead of GetResource calls.
  1240.         
  1241.         Using the file spec that we got from the CFMInitialization routine, open
  1242.         our resource fork.
  1243.  
  1244.  
  1245.  
  1246.  
  1247. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1248. static OSStatus
  1249. LoadResources( struct usbPrinterPBStruct *pPrinterPB )
  1250. {
  1251.     short            rf = -1;                // class driver resource fork
  1252.     OSStatus        err;
  1253.  
  1254.     //
  1255.     //    open the resource fork of this class driver
  1256.     //
  1257.     rf = FSpOpenResFile( &printerClassDriverFileSpec,fsRdPerm );
  1258.     err = ResError();
  1259.     
  1260.     //
  1261.     //    load the DRVR that we'll stick in the unit table
  1262.     //
  1263.     pPrinterPB->hDrvr = NULL;
  1264.     if ( err == noErr )
  1265.     {
  1266.         pPrinterPB->hDrvr = (DRVRHeaderHandle) Get1Resource( 'DRVR',  kUSBParallelDrvrRsrcID );
  1267.         if ( pPrinterPB->hDrvr != NULL )
  1268.             DetachResource( (Handle) pPrinterPB->hDrvr );
  1269.         err = ResError();
  1270.     }
  1271.     
  1272.     if ( rf != -1 )
  1273.         CloseResFile( rf );
  1274.     
  1275.     return err;
  1276. }
  1277.  
  1278. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1279.     Name:        InstallDrivers
  1280.  
  1281.     Input Parameters:
  1282.         pPrinterPB
  1283.         
  1284.     Output Parameters:
  1285.         OSStatus            error code
  1286.         
  1287.     Description:
  1288.         install read and write drivers in the unit table
  1289.             we have separate drivers so that we can support a full-duplex protocol
  1290.         rename the driver we just installed (so multiple copies don't conflict)
  1291.         We use the DRVR -refnum-1 so that the driver name has the same hex chars
  1292.             as the driver number (for manual verification in MacsBug)
  1293.  
  1294.  
  1295.  
  1296.  
  1297.  
  1298.  
  1299. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1300. static OSStatus
  1301. InstallDrivers( struct usbPrinterPBStruct *pPrinterPB )
  1302. {
  1303.     //
  1304.     //    install the driver in the unit table
  1305.     //    rename the driver we just installed (so multiple copies don't conflict)
  1306.     //    
  1307.     short            refNum;                // DRVR refNum
  1308.     OSStatus        err =  paramErr;    // couldn't find driver
  1309.  
  1310.     if ( pPrinterPB->hDrvr != NULL )
  1311.         err = TradInstallDriverFromHandle( pPrinterPB->hDrvr, kMinDrvrUnitNumber, TradHighestUnitNumber() + 1, &pPrinterPB->outRefNum );
  1312.  
  1313.     if ( err == noErr )
  1314.     {
  1315.         UnitNumber        unit;
  1316.         DriverFlags        flags;
  1317.         DRVRHeaderPtr    hdr;
  1318.         unsigned char    *suffix,        // append "In" and "Out"
  1319.                             *infix;        // driver reference number follows the ".USB"
  1320.  
  1321.         TradGetDriverInformation( pPrinterPB->outRefNum, &unit, &flags, pPrinterPB->driverOutName, &hdr );
  1322.         BlockMove( pPrinterPB->driverOutName, pPrinterPB->driverInName, 1 + pPrinterPB->driverOutName[0] );
  1323.         
  1324.         suffix = pPrinterPB->driverOutName + pPrinterPB->driverOutName[0] - 2;
  1325.         infix = pPrinterPB->driverOutName + kDrvrFirstDigit;
  1326.         infix[0] = HiHex( -pPrinterPB->outRefNum -1 );
  1327.         infix[1] = LoHex( -pPrinterPB->outRefNum -1 );
  1328.         suffix[0] = 'O';
  1329.         suffix[1] = 'u';
  1330.         suffix[2] = 't';
  1331.         TradRenameDriver( pPrinterPB->outRefNum, pPrinterPB->driverOutName );
  1332.         //
  1333.         //    set the driver data to point to our parameter block
  1334.         //
  1335.         err = OpenDriver( pPrinterPB->driverOutName, &refNum );
  1336.         if ( err == noErr )
  1337.         {
  1338.             struct usbPrinterPBStruct *param = pPrinterPB;
  1339.             err = Control( refNum, kDrvrPrivateSetStorage, ¶m );
  1340.             CloseDriver( refNum );
  1341.         }
  1342.         err = TradInstallDriverFromHandle( pPrinterPB->hDrvr, kMinDrvrUnitNumber, TradHighestUnitNumber() + 1, &pPrinterPB->inRefNum );
  1343.         if ( err == noErr )
  1344.         {
  1345.             
  1346.             suffix = pPrinterPB->driverInName + pPrinterPB->driverInName[0] - 1;
  1347.             infix = pPrinterPB->driverInName + kDrvrFirstDigit;
  1348.             infix[0] = HiHex( -pPrinterPB->inRefNum -1 );
  1349.             infix[1] = LoHex( -pPrinterPB->inRefNum -1 );
  1350.             suffix[0] = 'I';
  1351.             suffix[1] = 'n';
  1352.             TradRenameDriver( pPrinterPB->inRefNum, pPrinterPB->driverInName );
  1353.             //
  1354.             //    set the driver data to point to our parameter block
  1355.             //
  1356.             err = OpenDriver( pPrinterPB->driverInName, &refNum );
  1357.             if ( err == noErr )
  1358.             {
  1359.                 struct usbPrinterPBStruct *param = pPrinterPB;
  1360.                 err = Control( refNum, kDrvrPrivateSetStorage, ¶m );
  1361.                 CloseDriver( refNum );
  1362.             }
  1363.         }
  1364.     }
  1365.     
  1366.     return err;
  1367. }
  1368.  
  1369. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1370.     Name:        GetCapability
  1371.  
  1372.     Input Parameters:    
  1373.         
  1374.     Output Parameters:
  1375.         
  1376.     Description:
  1377.         Asynchronous completion.
  1378.  
  1379.  
  1380.  
  1381. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1382. static void
  1383. GetCapability( struct usbPrinterPBStruct *pPrinterPB, unsigned char *p, short length )
  1384. {
  1385.     //
  1386.     //    queue a transaction to retrieve the 1284 capability string
  1387.     //        we must have assigned the interface by this point since the capability string
  1388.     //        may vary with the interface
  1389.     //
  1390.     OSStatus        err;
  1391.     USBPB            *pb = &pPrinterPB->pb;
  1392.  
  1393.     SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  1394.     
  1395.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  1396.     pb->usbBuffer = 0;
  1397.     pb->usbActCount = 0;
  1398.     pb->usbReqCount = 0;
  1399.  
  1400.     pb->usb.cntl.BRequest = kUSBPrintClassGetDeviceID;
  1401.     pb->usb.cntl.WValue = 0;            // configuration
  1402.     pb->usb.cntl.WIndex = (pPrinterPB->interfaceNumber<<8) | pPrinterPB->alternateSetting;
  1403.  
  1404.     pb->usbReqCount = length;
  1405.     pb->usbBuffer = p;
  1406.  
  1407.     pb->usbRefcon |= kTransactionPending;
  1408.     pb->usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  1409.     err = USBDeviceRequest(pb);
  1410.     if(immediateError(err))
  1411.     {
  1412.         USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"GetCapability", 0);
  1413.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1414.         pb->usbRefcon |= kReturnFromDriver;
  1415.     }
  1416. }
  1417.  
  1418. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1419.     Name:        IsLucentCable
  1420.  
  1421.     Input Parameters:    
  1422.         dev            USB device descriptor
  1423.         
  1424.     Output Parameters:
  1425.         Return 1 if the USB device is a USB-parallel cable
  1426.         
  1427.     Description:
  1428.         
  1429.  
  1430.  
  1431.  
  1432. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1433. static short
  1434. IsLucentCable( USBDeviceDescriptor    *dev )
  1435. {
  1436.     return ( USBToHostWord(dev->vendor) == 0x47E && USBToHostWord(dev->product) == 0x1001 )? 1: 0;
  1437. }
  1438.  
  1439.  
  1440. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1441.     Name:        GetInterface
  1442.  
  1443.     Input Parameters:    
  1444.         
  1445.     Output Parameters:
  1446.         
  1447.     Description:
  1448.         Asynchronous completion.
  1449.  
  1450.  
  1451.  
  1452. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1453. static void
  1454. GetInterface( USBPB *pb, UInt8 *alt )
  1455. {
  1456.     //
  1457.     //    make sure we account for any alternate interface currently in use by the device
  1458.     //
  1459.     OSStatus    err;
  1460.  
  1461.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBStandard, kUSBInterface);
  1462.  
  1463.     pb->usb.cntl.BRequest = kUSBRqGetInterface;
  1464.     pb->usb.cntl.WValue = 0; 
  1465.     pb->usb.cntl.WIndex = 0;
  1466.  
  1467.     pb->usbReqCount = sizeof(UInt8);        // single byte is requested
  1468.     pb->usbBuffer = alt;
  1469.  
  1470.     pb->usbStatus = 0;
  1471.     pb->usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  1472.     pb->usbRefcon |= kTransactionPending;
  1473.  
  1474.     err = USBDeviceRequest(pb);
  1475.     if(immediateError(err))
  1476.     {
  1477.         USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"GetInterface", 0);
  1478.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1479.         pb->usbRefcon |= kReturnFromDriver;
  1480.     }
  1481. }
  1482.  
  1483.  
  1484. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1485.     Name:        ReadCompletion
  1486.  
  1487.     Input Parameters:    
  1488.         pb                        USB parameter block
  1489.         
  1490.     Output Parameters:
  1491.         <none>
  1492.  
  1493.     Description:
  1494.         USB read requests complete here.
  1495.         We dequeue the MacOS DRVR read requests
  1496.  
  1497.  
  1498.  
  1499.  
  1500.  
  1501.  
  1502.  
  1503.  
  1504. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1505. static void
  1506. ReadCompletion(USBPB *pb)
  1507. {
  1508.     //    call the user completion routine
  1509.     struct usbPrinterPBStruct
  1510.             *pPrinterPB =  (struct usbPrinterPBStruct    *) pb->usbRefcon;
  1511.     IOParamPtr     clientParam = pPrinterPB->readDrvr.pb;
  1512.     OSStatus        err = pb->usbStatus;
  1513.     DCtlPtr            ctlLocal;
  1514.  
  1515. #if MACSBUG_ON_READ_COMPLETE
  1516.     Str255    text;
  1517.     sprintf( (char *)text, " PrinterClass Read Complete(%d): %d", pb->usbStatus, pb->usbActCount );
  1518.     text[0] = CStrLen((char *)text); // c2pstr
  1519.     DebugStr( text );
  1520. #endif
  1521.  
  1522. #if DOUBLE_BUFFER
  1523.     //
  1524.     //    copy the user data from our page aligned buffer
  1525.     //
  1526.     USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion - bytes read  " , (UInt32)pb->usbActCount );
  1527.  
  1528.     if ( pb->usbActCount > 0 )
  1529.         BlockCopy( pPrinterPB->pageReadAlignedBuffer, clientParam->ioBuffer + clientParam->ioActCount, pb->usbActCount );
  1530. #endif
  1531.     //    update the amount of data actually transferred
  1532.     clientParam->ioActCount += pb->usbActCount;
  1533.  
  1534.     switch( pb->usbStatus )
  1535.     {
  1536.         //
  1537.         //    only retry low level hardware problems
  1538.         //        note: abort transactions will end up here as well
  1539.         //
  1540.     case kUSBLinkErr:
  1541.     case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  1542.     case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  1543.     case kUSBDataToggleErr:                        /*  Pipe stall, Bad data toggle */
  1544.     case kUSBNotRespondingErr:                    /*  Pipe stall, No device, device hung */
  1545.     case kUSBPIDCheckErr:                        /*  Pipe stall, PID CRC error */
  1546.     case kUSBWrongPIDErr:                        /*  Pipe stall, Bad or wrong PID */
  1547.         if (  --(pPrinterPB->readRetryCount) > 0 ) 
  1548.         {
  1549.             // we got an error, and we still want to retry, clear any stalls
  1550.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion retry" , pb->usbStatus );
  1551.             USBClearPipeStallByReference(pPrinterPB->readPipeRef);
  1552.             pb->usbStatus = noErr;
  1553.         }
  1554.         break;
  1555.     case kUSBAbortedError:                        /* user cancel, or hot unplug */
  1556.         USBClearPipeStallByReference(pPrinterPB->readPipeRef);
  1557.         USBClearPipeStallByReference(pPrinterPB->deviceRef);
  1558.         break;
  1559.         //
  1560.         //    any other error will be reported to the client
  1561.         //
  1562.     default:
  1563.     case noErr:
  1564.         break;
  1565.     }
  1566.     if ( pb->usbStatus == noErr &&                                     // there were no problems
  1567.         pb->usbActCount >= pb->usbReqCount &&                        // we got all the data we requested
  1568.         clientParam->ioActCount < clientParam->ioReqCount )    // we still want more data
  1569.     {
  1570.         //
  1571.         //    haven't finish the client's request
  1572.         //        update the pointers and start another bulk read transaction
  1573.         //
  1574. #if LOCK_MEMORY
  1575.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1576.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"ReadCompletion UnlockMem failed" ) );
  1577. #endif
  1578.         pb->usbBuffer = clientParam->ioBuffer + clientParam->ioActCount;
  1579.         pb->usbReqCount = clientParam->ioReqCount - clientParam->ioActCount;
  1580. #if MAX_USB_TRANSFER_SIZE
  1581.         if ( pb->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1582.             pb->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1583. #endif
  1584. #if DOUBLE_BUFFER
  1585.         //
  1586.         //    make sure we have enough room in our buffer
  1587.         //
  1588.         if ( pb->usbReqCount > pPrinterPB->pageReadAlignedBufferSize )
  1589.             pb->usbReqCount = pPrinterPB->pageReadAlignedBufferSize;
  1590.         pb->usbBuffer = pPrinterPB->pageReadAlignedBuffer;
  1591. #endif
  1592. #if LOCK_MEMORY
  1593.         err = LockMemory( pb->usbBuffer, pb->usbReqCount );
  1594.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"ReadCompletion LockMem failed" ) );
  1595.         if ( err == noErr )
  1596. #endif
  1597.         err = SafeUSBBulkRead( pb );
  1598.         if ( immediateError(err) )
  1599.         {
  1600.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion finish immed err" , err );
  1601.  
  1602.             pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1603.             if ( pPrinterPB->readDrvr.ctl != NULL )
  1604.             {
  1605.                 ctlLocal = pPrinterPB->readDrvr.ctl;
  1606.                 pPrinterPB->readDrvr.ctl = NULL;
  1607.                 CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, err, clientParam, ctlLocal ); 
  1608.             }
  1609.         }
  1610.     }
  1611.     else
  1612.     {
  1613.         //
  1614.         //        either we have an error which we're not retrying
  1615.         //            or we successfully completed
  1616.         //
  1617. #if LOCK_MEMORY
  1618.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1619.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"ReadCompletion concluded UnlockMem failed" ) );
  1620. #endif
  1621.         IF_DEBUG( if (pb->usbStatus != noErr) USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"ReadCompletion Error" , pb->usbStatus ) );
  1622.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1623.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"readDrvr.ctl = " , (UInt32)pPrinterPB->readDrvr.ctl );
  1624.         if ( pPrinterPB->readDrvr.ctl != NULL )
  1625.         {
  1626.             ctlLocal = pPrinterPB->readDrvr.ctl;
  1627.             pPrinterPB->readDrvr.ctl = NULL;
  1628.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, ctlLocal); 
  1629.         }
  1630.         else
  1631.         {
  1632.             IF_DEBUG( DebugStr( kPStrPrinterDriverName"ReadCompletion() pPrinterPB->readDrvr.ctl == NULL" ) );
  1633.         }
  1634.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB PRint, read completion do suspend resume" , pb->usbReference);
  1635.         USBPrintDoSuspendResume(pPrinterPB->interfaceRef);
  1636.     }
  1637. }
  1638.  
  1639.  
  1640. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1641.     Name:        WriteCompletion
  1642.  
  1643.     Input Parameters:    
  1644.         pb                        USB parameter block
  1645.         
  1646.     Output Parameters:
  1647.         <none>
  1648.  
  1649.     Description:
  1650.         USB write requests complete here.
  1651.         We dequeue the MacOS DRVR write requests
  1652.  
  1653.         when breaking up transactions we use ioActCount to determine how much remains 
  1654.                 of the original request and where the next request begins
  1655.         if we've failed with a USB error
  1656.             usbActCount indicates how much data has been transferred with the current request
  1657.             and if the retry count hasn't been exceeded
  1658.                 we proceed as if we'd just requested that much in this transactions
  1659.         note the retry count is cumulative for the original client request
  1660.             not for each usb transaction
  1661.  
  1662.  
  1663.  
  1664.  
  1665.  
  1666.  
  1667.  
  1668.  
  1669.  
  1670.  
  1671. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1672. static void
  1673. WriteCompletion(USBPB *pb)
  1674. {
  1675.     //    call the user completion routine
  1676.     struct usbPrinterPBStruct
  1677.                     *pPrinterPB =  (struct usbPrinterPBStruct    *) pb->usbRefcon;
  1678.     IOParamPtr     clientParam = pPrinterPB->writeDrvr.pb;
  1679.     DCtlPtr            ctlLocal;
  1680.     OSStatus        err = pb->usbStatus;
  1681.  
  1682. #if MACSBUG_ON_WRITE_COMPLETE
  1683.     Str255    text;
  1684.     sprintf( (char *)text, " PrinterClass Write Complete(%d): %d", pb->usbStatus, pb->usbActCount );
  1685.     text[0] = CStrLen((char *)text); // c2pstr
  1686.     DebugStr( text );
  1687. #endif
  1688.  
  1689.     //    update the amount of data actually transferred
  1690.     clientParam->ioActCount += pb->usbActCount;
  1691.     USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion - bytes written  " , (UInt32)pb->usbActCount);
  1692.  
  1693.     switch( pb->usbStatus )
  1694.     {
  1695.         //
  1696.         //    only retry low level hardware problems
  1697.         //        note: abort transactions will end up here as well
  1698.         //
  1699.     case kUSBLinkErr:
  1700.     case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  1701.     case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  1702.     case kUSBDataToggleErr:                        /*  Pipe stall, Bad data toggle */
  1703.     case kUSBNotRespondingErr:                    /*  Pipe stall, No device, device hung */
  1704.     case kUSBPIDCheckErr:                        /*  Pipe stall, PID CRC error */
  1705.     case kUSBWrongPIDErr:                        /*  Pipe stall, Bad or wrong PID */
  1706.         if (  --(pPrinterPB->writeRetryCount) > 0 ) 
  1707.         {
  1708.             // we got an error, and we still want to retry, clear any stalls
  1709.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion retry" , pb->usbStatus );
  1710.             USBClearPipeStallByReference(pPrinterPB->writePipeRef);
  1711.             pb->usbStatus = noErr;
  1712.             
  1713.             USBExpertStatusLevel(3, pb->usbReference, kPStrPrinterDriverName"**** WriteCompletion clearing endpoint halt *****" , pb->usbStatus );
  1714.             ClearEndpointHalt(pb);    // Sets up PB
  1715.             USBDeviceRequest(pb);
  1716.             return;
  1717.             
  1718.         }
  1719.         break;
  1720.     case kUSBAbortedError:                        /* user cancel, or hot unplug */
  1721.         USBClearPipeStallByReference(pPrinterPB->writePipeRef);
  1722.         USBClearPipeStallByReference(pPrinterPB->deviceRef);
  1723.         break;
  1724.         //
  1725.         //    any other error will be reported to the client
  1726.         //
  1727.     default:
  1728.     case noErr:
  1729.         break;
  1730.     }
  1731.  
  1732.     if ( pb->usbStatus == noErr && clientParam->ioActCount < clientParam->ioReqCount )
  1733.     {
  1734.         //
  1735.         //    haven't finish the client's request
  1736.         //        update the pointers and start another bulkOut transaction
  1737.         //
  1738. #if LOCK_MEMORY
  1739.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1740.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"WriteCompletion UnlockMem failed" ) );
  1741. #endif
  1742.         pb->usbBuffer = clientParam->ioBuffer + clientParam->ioActCount;
  1743.         pb->usbReqCount = clientParam->ioReqCount - clientParam->ioActCount;
  1744. #if MAX_USB_TRANSFER_SIZE
  1745.         if ( pb->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1746.             pb->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1747. #endif
  1748. #if DOUBLE_BUFFER
  1749.         //
  1750.         //    make sure we have enough room in our buffer
  1751.         //    then copy the user data into our page aligned buffer
  1752.         //
  1753.         if ( pb->usbReqCount > pPrinterPB->pageWriteAlignedBufferSize )
  1754.             pb->usbReqCount = pPrinterPB->pageWriteAlignedBufferSize;
  1755.             
  1756.         BlockCopy( pb->usbBuffer, pPrinterPB->pageWriteAlignedBuffer, pb->usbReqCount );
  1757.         pb->usbBuffer = pPrinterPB->pageWriteAlignedBuffer;
  1758.         
  1759. #endif
  1760. #if LOCK_MEMORY
  1761.         err = LockMemory( pb->usbBuffer, pb->usbReqCount );
  1762.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"WriteCompletion LockMem failed" ) );
  1763.         if ( err == noErr )
  1764. #endif
  1765.             err = SafeUSBBulkWrite( pb );
  1766.         if ( immediateError(err) )
  1767.         {
  1768.             USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion finish immed err" , err );
  1769.  
  1770.             pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1771.             if ( pPrinterPB->writeDrvr.ctl != NULL )
  1772.             {
  1773.                 ctlLocal = pPrinterPB->writeDrvr.ctl;
  1774.                 pPrinterPB->writeDrvr.ctl = NULL;
  1775.                 CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, err, clientParam, ctlLocal ); 
  1776.             }
  1777.         }
  1778.     }
  1779.     else
  1780.     {
  1781.         //
  1782.         //        either we have an error which we're not retrying
  1783.         //            or we successfully completed
  1784.         //
  1785. #if LOCK_MEMORY
  1786.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1787.         IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"WriteCompletion concluded UnlockMem failed" ) );
  1788. #endif
  1789.  
  1790.         IF_DEBUG( if (pb->usbStatus != noErr) USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"WriteCompletion Error" , pb->usbStatus ) );
  1791.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1792.  
  1793.  
  1794.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, kPStrPrinterDriverName"writeDrvr.ctl = " , (UInt32)pPrinterPB->writeDrvr.ctl );
  1795.         if ( pPrinterPB->writeDrvr.ctl != NULL )
  1796.         {
  1797.             ctlLocal = pPrinterPB->writeDrvr.ctl;
  1798.             pPrinterPB->writeDrvr.ctl = NULL;
  1799.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, ctlLocal ); 
  1800.         }
  1801.         else
  1802.         {
  1803.             IF_DEBUG( DebugStr( kPStrPrinterDriverName"WriteCompletion() pPrinterPB->writeDrvr.ctl == NULL" ) );
  1804.         }
  1805.         USBExpertStatusLevel(kDebugStatusLevel, pb->usbReference, "\pUSB PRint, write completion do suspend resume" , pb->usbReference );
  1806.         USBPrintDoSuspendResume(pPrinterPB->interfaceRef);
  1807.     }
  1808. }
  1809.  
  1810. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1811.     Name:        QueueRead
  1812.  
  1813.     Input Parameters:    
  1814.         pb                        MacOS device manager parameter block
  1815.         ctl                    device manager dCtl block
  1816.         pPrinterPB            current printing device class's storage
  1817.         
  1818.     Output Parameters:
  1819.         <none>
  1820.  
  1821.     Description:
  1822.         MacOS DRVR read requests are re-queued here to the USB
  1823.         Since we only allow one read request pending at a time, we're able
  1824.         to use the USB refCon to point to our class driver's storage.
  1825.  
  1826.  
  1827.  
  1828.  
  1829. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1830. void
  1831. QueueRead( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  1832. {    
  1833.     OSStatus    err;
  1834.     USBPB        *usbprint = &pPrinterPB->in;
  1835.     
  1836. #if MACSBUG_ON_READ
  1837.     Str255    text;
  1838.  
  1839.     sprintf( (char *)text, " PrinterClass Read: %d @ %08x", pb->ioReqCount, pb->ioBuffer );
  1840.     text[0] = CStrLen((char *)text); // c2pstr
  1841.     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  1842.     DebugStr( text );
  1843. #endif
  1844.  
  1845.     // BT - 15Jun99, if we're not currently awake, delay this until we are.
  1846.     if(currentlyAre == kUSBPrintSuspended)
  1847.     {
  1848.         pb->ioResult = ioInProgress;
  1849.         USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, delaying read for resume", 0 );
  1850.         RpPrinterPB = pPrinterPB;
  1851.         Rctl = ctl;
  1852.         Rpb = pb;
  1853.         if( (currentlyAre != kUSBPrintSuspended) && (Rpb != nil) )
  1854.         {
  1855.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, resumed while we wern't looking", 0 );
  1856.             // resumed and executed this while we were doing this.
  1857.             return;
  1858.         }
  1859.         else
  1860.         {
  1861.             // now wait for resume to happen
  1862.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, let resume take over", 0 );
  1863.             return;
  1864.         }        
  1865.     }
  1866.  
  1867.  
  1868.     pb->ioActCount = 0;        // nothing transfered yet
  1869.     if ( pPrinterPB->terminating )
  1870.         pb->ioResult = abortErr;
  1871.     else
  1872.     {
  1873.  
  1874.         pPrinterPB->readRetryCount = 5;
  1875.         pPrinterPB->readDrvr.pb= pb;
  1876.         pPrinterPB->readDrvr.ctl = ctl;
  1877.         if (( pPrinterPB->readPipeRef != NULL ) && (pPrinterPB->printerConfigured))
  1878.         {
  1879.             SetNullUSBParamBlock( pPrinterPB->readPipeRef,  usbprint );
  1880.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Set up to do bulk read", pb->ioReqCount );
  1881.             usbprint->usbActCount = 0;
  1882.             usbprint->usbBuffer = pb->ioBuffer;
  1883.             usbprint->usbReqCount = pb->ioReqCount;
  1884.  
  1885. #if MAX_USB_TRANSFER_SIZE
  1886.             //
  1887.             //    the completion routine will queue another BulkWrite until we exhaust the data
  1888.             //        or there is an error which can't be retried
  1889.             //
  1890.             if ( usbprint->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1891.                 usbprint->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1892. #endif
  1893. #if DOUBLE_BUFFER
  1894.             //
  1895.             //    make sure we have enough room in our buffer
  1896.             //    then copy the user data into our page aligned buffer
  1897.             //
  1898.             if ( usbprint->usbReqCount > pPrinterPB->pageReadAlignedBufferSize )
  1899.                 usbprint->usbReqCount = pPrinterPB->pageReadAlignedBufferSize;
  1900.             usbprint->usbBuffer = pPrinterPB->pageReadAlignedBuffer;
  1901. #endif
  1902.             usbprint->usbRefcon = (unsigned long) pPrinterPB;
  1903.             usbprint->usbCompletion = (USBCompletion) ReadCompletion;
  1904.             
  1905.             pb->ioResult = ioInProgress;
  1906. #if LOCK_MEMORY
  1907.             err = LockMemory( usbprint->usbBuffer, usbprint->usbReqCount );
  1908.             IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"QueueRead LockMem failed" ) );
  1909.             if ( err == noErr )
  1910. #endif
  1911.             err = SafeUSBBulkRead( usbprint );
  1912.             if ( immediateError(err) )
  1913.             {
  1914.                 USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Error doing bulk read",err );
  1915.                 IF_DEBUG( DebugStr( USBStatusStr(err, kPString) ) );
  1916.                 usbprint->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1917.                 pb->ioResult = err;
  1918.             }
  1919.         }
  1920.         else
  1921.         {
  1922.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Read to unopened pipe" , usbprint->usbStatus ) ;
  1923.             pb->ioResult = abortErr;
  1924.         }
  1925.     }
  1926. }
  1927.  
  1928. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1929.     Name:        QueueWrite
  1930.  
  1931.     Input Parameters:    
  1932.         pb                        MacOS device manager parameter block
  1933.         ctl                    device manager dCtl block
  1934.         pPrinterPB            current printing device class's storage
  1935.         
  1936.     Output Parameters:
  1937.         <none>
  1938.  
  1939.     Description:
  1940.         MacOS DRVR write requests are re-queued here to the USB
  1941.         Since we only allow one read request pending at a time, we're able
  1942.         to use the USB refCon to point to our class driver's storage.
  1943.  
  1944.  
  1945.  
  1946. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1947. void
  1948. QueueWrite( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  1949. {
  1950.     OSStatus    err;
  1951.     USBPB        *usbprint = &pPrinterPB->out;
  1952. #if VIRTUAL_MEMORY_CHECK
  1953.     //
  1954.     //    dump the VM table
  1955.     //
  1956.     Str255                        text;
  1957.     LogicalToPhysicalTable        *vmTable;
  1958.     MemoryBlock                    *physical;
  1959.     unsigned long                vmCount,
  1960.                                 vmEntry,
  1961.                                 vmTblLength;
  1962. #endif
  1963.  
  1964. #if MACSBUG_ON_WRITE
  1965.     Str255    text;
  1966.     sprintf( (char *)text, " "kCStrPrinterDriverName"%d @ %08x", pb->ioReqCount, pb->ioBuffer );
  1967.     text[0] = CStrLen((char *)text); // c2pstr
  1968.     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  1969.     DebugStr( text );
  1970. #endif
  1971.  
  1972.     // BT - 15Jun99, if we're not currently awake, delay this until we are.
  1973.     if(currentlyAre == kUSBPrintSuspended)
  1974.     {
  1975.         pb->ioResult = ioInProgress;
  1976.         USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, delaying write for resume", 0 );
  1977.  
  1978.         WpPrinterPB = pPrinterPB;
  1979.         Wctl = ctl;
  1980.         Wpb = pb;
  1981.         if( (currentlyAre != kUSBPrintSuspended) && (Wpb != nil) )
  1982.         {
  1983.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, resumed while we wern't looking", 0 );
  1984.             // resumed and executed this while we were doing this.
  1985.         }
  1986.         else
  1987.         {
  1988.             // now wait for resume to happen
  1989.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, "\pUSB Print, let resume take over", 0 );
  1990.             return;
  1991.         }        
  1992.     }
  1993.  
  1994.  
  1995.  
  1996. #if VIRTUAL_MEMORY_CHECK
  1997.     //
  1998.     //    this check current won't compile without runtime error: need to lock memory, but lock has moved
  1999.     //
  2000.     sprintf( (char *)text, " "kCStrPrinterDriverName"Write: %d @ %08x", pb->ioReqCount, pb->ioBuffer );
  2001.     text[0] = CStrLen((char *)text); // c2pstr
  2002.     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  2003.     
  2004.     vmCount = 127;
  2005.     vmTblLength = (vmCount+1)*sizeof(MemoryBlock);
  2006.     vmTable = (LogicalToPhysicalTable *) NewPtrSys( vmTblLength );
  2007.     LockMemory( vmTable, vmTblLength );
  2008.     LockMemory( &vmCount, sizeof(unsigned long) );
  2009.     vmTable->logical.address = pb->ioBuffer;
  2010.     vmTable->logical.count = pb->ioReqCount;
  2011.     err = GetPhysical( vmTable, &vmCount );
  2012.     
  2013.     if ( err == noErr )
  2014.     {
  2015.         for ( vmEntry = 0, physical = &vmTable->physical[0]; vmEntry < vmCount; ++vmEntry , ++physical)
  2016.         {
  2017.             sprintf( (char *)text, " "kCStrPrinterDriverName"Write: VM @%08x (%d)", physical->address, physical->count );
  2018.             text[0] = CStrLen((char *)text); // c2pstr
  2019.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  2020.         }
  2021.     }
  2022.     UnlockMemory( vmTable, vmTblLength );
  2023.     UnlockMemory( &vmCount, sizeof(unsigned long) );
  2024. #endif
  2025.     pb->ioActCount = 0;        // nothing transfered yet
  2026.  
  2027.  
  2028.     usbprint->usbStatus = noErr;    // forget about abort and things from previous writes
  2029.     if ( pPrinterPB->terminating )
  2030.         pb->ioResult = abortErr;
  2031.     else
  2032.     {
  2033.         pPrinterPB->writeRetryCount = 5;
  2034.         pPrinterPB->writeDrvr.pb = pb;
  2035.         pPrinterPB->writeDrvr.ctl = ctl;
  2036.         if (( pPrinterPB->writePipeRef != NULL ) && (pPrinterPB->printerConfigured))
  2037.         {
  2038.             SetNullUSBParamBlock( pPrinterPB->writePipeRef,  usbprint );
  2039.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Set up to do bulk write", pb->ioReqCount );
  2040.             usbprint->usbActCount = 0;
  2041.             usbprint->usbBuffer = pb->ioBuffer;
  2042.             usbprint->usbRefcon = (unsigned long) pPrinterPB;
  2043.             usbprint->usbCompletion = (USBCompletion) WriteCompletion;
  2044.             
  2045. #if MAX_USB_TRANSFER_SIZE
  2046.             //
  2047.             //    the completion routine will queue another BulkWrite until we exhaust the data
  2048.             //        or there is an error which can't be retried
  2049.             //
  2050.             if ( pb->ioReqCount > MAX_USB_TRANSFER_SIZE )
  2051.                 usbprint->usbReqCount = MAX_USB_TRANSFER_SIZE;
  2052.             else
  2053. #endif
  2054.                 usbprint->usbReqCount = pb->ioReqCount;
  2055.     
  2056.  
  2057. #if DOUBLE_BUFFER
  2058.             //
  2059.             //    make sure we have enough room in our buffer
  2060.             //    then copy the user data into our page aligned buffer
  2061.             //
  2062.             if ( usbprint->usbReqCount > pPrinterPB->pageWriteAlignedBufferSize )
  2063.                 usbprint->usbReqCount = pPrinterPB->pageWriteAlignedBufferSize;
  2064.             BlockCopy( usbprint->usbBuffer, pPrinterPB->pageWriteAlignedBuffer, usbprint->usbReqCount );
  2065.             usbprint->usbBuffer = pPrinterPB->pageWriteAlignedBuffer;
  2066. #endif
  2067.             pb->ioResult = ioInProgress;
  2068.     
  2069. #if LOCK_MEMORY
  2070.             err = LockMemory( usbprint->usbBuffer, usbprint->usbReqCount );
  2071.             IF_DEBUG( if ( err != noErr ) DebugStr( kPStrPrinterDriverName"QueueWrite LockMem failed" ) );
  2072.             if ( err == noErr )
  2073. #endif
  2074.                 err = SafeUSBBulkWrite( usbprint );
  2075.             if ( immediateError(err) )
  2076.             {
  2077.                 USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Immediate error doing bulk write",0 );
  2078.                 IF_DEBUG( DebugStr( USBStatusStr(err, kPString) ) );
  2079.                 usbprint->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  2080.                 pb->ioResult = err;
  2081.             }
  2082.             //
  2083.             //    note our logging is one write for each the client request
  2084.             //        not one write for each usb transaction
  2085.             //
  2086.             LOGGING( fwrite( pb->ioBuffer, sizeof(char), pb->ioReqCount, logfile ) );
  2087.         }
  2088.         else
  2089.         {
  2090.             USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, kPStrPrinterDriverName"Write to unopened pipe" , usbprint->usbStatus );
  2091.             pb->ioResult = abortErr;
  2092.         }
  2093.     }
  2094. }
  2095.  
  2096.  
  2097. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2098.     Name:        Abort
  2099.  
  2100.     Input Parameters:    
  2101.         refNum            DRVR refnum
  2102.         pPrinterPB        current printing device class's storage
  2103.  
  2104.     Output Parameters:
  2105.         
  2106.     Description:
  2107.         Asynchronous completion.
  2108.         Note: USBAbortPipeByReference can leave the data toggle in the wrong state.
  2109.                 We need to abort both pipes, and then the client must soft reset the printer
  2110.                 to get the printer's data toggles correct.
  2111.         We prematurely call completion routines for active i/o so that CloseDriverSync
  2112.             will not hang the system after an abort, including hot unplug. This works out okay,
  2113.             since the request will be dequeued now, and when the i/o actually terminates
  2114.             the system will be called with an invalid queue element and then reject this second
  2115.             attempt to dequeue the i/o.
  2116.  
  2117.  
  2118.  
  2119.  
  2120. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2121. OSStatus
  2122. Abort( DriverRefNum refNum, struct usbPrinterPBStruct *pPrinterPB )
  2123. {
  2124.     OSStatus        err = noErr;
  2125.  
  2126.     //
  2127.     //    if there's any pending io this will call the completion routine
  2128.     //
  2129.     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB Print - Abort called" , 0);
  2130.     if (refNum == pPrinterPB->outRefNum)
  2131.     {
  2132.         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB Print - Abort called on out pipe" , 0);
  2133.         if ( pPrinterPB->in.usbCompletion != (USBCompletion) NULL )
  2134.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "***** Abort with write in progress" , 0);
  2135.         
  2136.         err = USBAbortPipeByReference( pPrinterPB->writePipeRef );
  2137.         err = USBClearPipeStallByReference( pPrinterPB->writePipeRef );
  2138.         
  2139.         if ( pPrinterPB->out.usbCompletion != (USBCompletion) NULL )
  2140.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, abortErr, pPrinterPB->writeDrvr.pb, pPrinterPB->writeDrvr.ctl ); 
  2141.     }
  2142.     
  2143.     if (refNum == pPrinterPB->inRefNum)
  2144.     {
  2145.         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB Print - Abort called on in pipe" , 0);
  2146.         if ( pPrinterPB->out.usbCompletion != (USBCompletion) NULL )
  2147.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "***** Abort with read in progress" , 0);
  2148.  
  2149.         err = USBAbortPipeByReference( pPrinterPB->readPipeRef );
  2150.         err = USBClearPipeStallByReference( pPrinterPB->readPipeRef );
  2151.  
  2152.         if ( pPrinterPB->in.usbCompletion != (USBCompletion) NULL )
  2153.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, abortErr, pPrinterPB->readDrvr.pb, pPrinterPB->readDrvr.ctl ); 
  2154.     }
  2155.     return err;
  2156. }
  2157.  
  2158.  
  2159. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2160.     Name:        CompletionProc
  2161.  
  2162.     Input Parameters:    
  2163.         pb                    USB param block ptr
  2164.     
  2165.     Output Parameters:
  2166.         
  2167.     Description:
  2168.         Asynchronous completion routine for DRVR requests.
  2169.  
  2170.  
  2171.  
  2172.  
  2173.  
  2174. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2175. static void 
  2176. CompletionProc(USBPB *pb)
  2177. {
  2178.     //    call the user completion routine
  2179.     struct usbPrinterPBStruct
  2180.                     *pPrinterPB = (struct usbPrinterPBStruct    *) pb->usbRefcon;
  2181.     IOParamPtr     clientParam = pPrinterPB->statusDrvr.pb;
  2182.  
  2183.     clientParam->ioActCount = pb->usbActCount;
  2184.  
  2185.     if ( pb->usbStatus != noErr ) 
  2186.     {
  2187.         USBClearPipeStallByReference(pb->usbReference);  // we got an error, try to clear any stalls
  2188.  
  2189.         IF_DEBUG( USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "CompletionProc Error" , pb->usbStatus ) );
  2190.         IF_DEBUG( USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, USBStatusStr(pb->usbStatus, kPString) , pb->usbStatus ) );
  2191.     }
  2192.  
  2193.     pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  2194.     if ( pPrinterPB->statusDrvr.ctl != NULL )
  2195.         CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, pPrinterPB->statusDrvr.ctl ); 
  2196. }
  2197.  
  2198. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2199.     Name:        CentronicsStatus
  2200.  
  2201.     Input Parameters:    
  2202.         pb                        MacOS device manager parameter block
  2203.         ctl                    device manager dCtl block
  2204.         pPrinterPB            current printing device class's storage
  2205.  
  2206.     Output Parameters:
  2207.         pStatusByte        
  2208.         
  2209.     Description:
  2210.         setup the device request for a USB printer class request one byte status.
  2211.  
  2212.  
  2213.  
  2214.  
  2215.  
  2216. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2217. static void
  2218. CentronicsStatus( USBPB *usbprint, Ptr buffer, short interfaceNumber )
  2219. {
  2220.     usbprint->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  2221.  
  2222.     usbprint->usb.cntl.BRequest = kUSBPrintClassGetCentronicsStatus;
  2223.     usbprint->usb.cntl.WValue = 0;
  2224.     usbprint->usb.cntl.WIndex = interfaceNumber;
  2225.  
  2226.     usbprint->usbReqCount = 1;
  2227.     usbprint->usbBuffer = buffer;
  2228. }
  2229.  
  2230. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2231.     Name:        ClearEndpointHalt
  2232.  
  2233.     Input Parameters:    
  2234.         usbprint                USB param block
  2235.  
  2236.     Output Parameters:
  2237.         
  2238.     Description:
  2239.         Setup the device request for a USB clear endpoint halt.
  2240.  
  2241. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2242. void
  2243. ClearEndpointHalt( USBPB *usbprint)
  2244. {
  2245.     usbprint->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBOut, kUSBStandard, kUSBEndpoint);
  2246.  
  2247.     usbprint->usb.cntl.BRequest = kUSBRqClearFeature;
  2248.     usbprint->usb.cntl.WValue = kUSBFeatureEndpointStall;
  2249.     usbprint->usbFlags = kUSBAddressRequest;
  2250.  
  2251.     usbprint->usbReqCount = 0;
  2252.     usbprint->usbBuffer = NULL;
  2253.     
  2254.  
  2255. }
  2256.  
  2257. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2258.     Name:        SoftReset
  2259.  
  2260.     Input Parameters:    
  2261.         usbprint                USB param block
  2262.         interfaceNumber
  2263.  
  2264.     Output Parameters:
  2265.         
  2266.     Description:
  2267.         Setup the device request for a USB printer class request soft reset.
  2268.  
  2269.  
  2270.  
  2271.  
  2272.  
  2273. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2274. void
  2275. SoftReset( USBPB *usbprint, short interfaceNumber )
  2276. {
  2277.     usbprint->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBOut, kUSBClass, kUSBOther);
  2278.  
  2279.     usbprint->usb.cntl.BRequest = kUSBPrintClassSoftReset;
  2280.     usbprint->usb.cntl.WValue = 0;
  2281.     usbprint->usb.cntl.WIndex = interfaceNumber;
  2282.  
  2283.     usbprint->usbReqCount = 0;
  2284.     usbprint->usbBuffer = NULL;
  2285.     
  2286.  
  2287. }
  2288.  
  2289. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2290.     Name:        CapabilityRequest
  2291.  
  2292.     Input Parameters:    
  2293.         usbprint            USB parameter block
  2294.         p                    result pointer
  2295.         length            amount of data allocated
  2296.         config
  2297.         interfaceNum
  2298.         alternateSetting
  2299.         
  2300.  
  2301.     Output Parameters:
  2302.         p                    result pointer
  2303.         length            amount of data allocated
  2304.         
  2305.     Description:
  2306.         setup the device request for a USB printer class request 1284 id string.
  2307.  
  2308.  
  2309.  
  2310.  
  2311.  
  2312. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2313. void
  2314. CapabilityRequest( USBPB *pb, Ptr p, long length, short configValue, short interfaceNumber, short alternateSetting  )
  2315. {
  2316.  
  2317.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  2318.  
  2319.     pb->usb.cntl.BRequest = kUSBPrintClassGetDeviceID;
  2320.     pb->usb.cntl.WValue = configValue;        // configuration
  2321.     pb->usb.cntl.WIndex = (interfaceNumber<<8) | alternateSetting;
  2322.  
  2323.     pb->usbReqCount = length;
  2324.     pb->usbBuffer = p;
  2325.  
  2326. }
  2327.  
  2328. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2329.     Name:        StatusControlRequests
  2330.  
  2331.     Input Parameters:    
  2332.         pb                        MacOS device manager parameter block
  2333.         ctl                    device manager dCtl block
  2334.         pPrinterPB            current printing device class's storage
  2335.  
  2336.     Output Parameters:
  2337.         
  2338.     Description:
  2339.         Asynchronous completion.
  2340.  
  2341.  
  2342.  
  2343.  
  2344. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2345.  
  2346. void
  2347. ControlStatusRequests( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  2348. {
  2349.  
  2350.     //
  2351.     //    queue a transaction to retrieve the centronics status
  2352.     //
  2353.     OSStatus    err;
  2354.     USBPB        *usbprint = &pPrinterPB->pb;
  2355.     Boolean        dosomething = false;
  2356.     
  2357. #if DEBUG
  2358.     Str255        text;
  2359.  
  2360.     sprintf( (char *)text, " PrinterClass ControlStatus: %d", ((CntrlParam *) pb)->csCode );
  2361.     text[0] = CStrLen((char *)text); // c2pstr
  2362.     USBExpertStatusLevel(kDebugStatusLevel, usbprint->usbReference, text, usbprint->usbStatus );
  2363. #endif
  2364.  
  2365.     if (pPrinterPB->terminating)
  2366.     {
  2367.         pb->ioResult = abortErr;
  2368.     }
  2369.     else
  2370.     {
  2371.         switch( ((CntrlParam *) pb)->csCode )
  2372.         {
  2373.         case kDrvrCentronicsStatus:
  2374.             dosomething = true;
  2375.             CentronicsStatus( usbprint,  *((Ptr *)((CntrlParam *) pb)->csParam), pPrinterPB->interfaceNumber );
  2376.             SetNullUSBParamBlock(pPrinterPB->deviceRef,  usbprint );
  2377.             break;
  2378.             
  2379.             
  2380.         case kDrvr1284IdString:
  2381.             dosomething = true;
  2382.             CapabilityRequest( usbprint,
  2383.                                     *((Ptr *)((CntrlParam *) pb)->csParam),
  2384.                                     *((long *) &((CntrlParam *) pb)->csParam[4]),
  2385.                                     0,        // configuration
  2386.                                     pPrinterPB->interfaceNumber,
  2387.                                     pPrinterPB->alternateSetting);
  2388.             SetNullUSBParamBlock(pPrinterPB->deviceRef,  usbprint );
  2389.             break;
  2390.             
  2391.         case kDrvrSoftReset:
  2392.             dosomething = true;
  2393.             if ( ((CntrlParam *) pb)->ioCRefNum == pPrinterPB->outRefNum )
  2394.             {
  2395.                 SetNullUSBParamBlock(pPrinterPB->writePipeRef,  usbprint );
  2396.             }
  2397.             else 
  2398.             {
  2399.                 SetNullUSBParamBlock(pPrinterPB->readPipeRef,  usbprint );
  2400.             }
  2401.             ClearEndpointHalt( usbprint );
  2402.             break;
  2403.         
  2404.         case kDrvrPrivateLog:
  2405.             // BT - 15Jun99, print a message in the log for the 68k code.
  2406.             USBExpertStatusLevel(((CntrlParam *) pb)->csParam[2], pPrinterPB->deviceRef, *(unsigned char **)(((CntrlParam *) pb)->csParam), *((long *)&((CntrlParam *) pb)->csParam[4]) );
  2407.             return;
  2408.             break;
  2409.         
  2410.         case kDrvrPrivateOpnClose:
  2411.             // BT - 15Jun99, Open or close has been called, arrange for suspend or resume.
  2412.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, "\pUSB print driver kDrvrPrivateOpnClose", ((CntrlParam *) pb)->csParam[0] == 0);
  2413.             // If csParam[0] is 1 we're being opened, if 0 we're being closed
  2414.             if(((CntrlParam *) pb)->csParam[0] == 1)
  2415.             {
  2416.                 openRef++;
  2417.                 wantToBe = kUSBPrintResumed;
  2418.                 // We're being opened
  2419.             }
  2420.             else if(((CntrlParam *) pb)->csParam[0] == 0)
  2421.             {
  2422.                 if (--openRef < 0) 
  2423.                     openRef = 0;
  2424.                 
  2425.                 if (!openRef)  // is this the last close?
  2426.                     wantToBe = kUSBPrintSuspended;
  2427.                 else
  2428.                     wantToBe = kUSBPrintResumed;
  2429.             }
  2430.             else
  2431.             {
  2432.                 USBExpertStatusLevel(2, pPrinterPB->deviceRef, "\pUSB print driver kDrvrPrivateOpnClose unknown message", ((CntrlParam *) pb)->csParam[0] == 0);
  2433.             }
  2434.             USBPrintDoSuspendResume(pPrinterPB->interfaceRef);
  2435.             return;
  2436.             break;
  2437.         default:
  2438.             break;
  2439.         }
  2440.     
  2441.         if ( !dosomething )
  2442.             pb->ioResult = paramErr;
  2443.         else
  2444.         {
  2445.             usbprint->usbActCount = 0;
  2446.             usbprint->usbCompletion = (USBCompletion)CompletionProc;
  2447.             usbprint->usbRefcon = (unsigned long) pPrinterPB;
  2448.         
  2449.             pb->ioResult = ioInProgress;
  2450.             pPrinterPB->statusDrvr.pb = pb;
  2451.             pPrinterPB->statusDrvr.ctl = ctl;
  2452.         
  2453.             err = USBDeviceRequest(usbprint);
  2454.             if(immediateError(err))
  2455.             {
  2456.                 USBExpertFatalError(usbprint->usbReference, err, kPStrPrinterDriverName"StatusControlRequests", 0);
  2457.                 usbprint->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  2458.                 pb->ioResult = err;
  2459.             }
  2460.         }
  2461.     }
  2462. }
  2463.  
  2464.  
  2465. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2466.     Name:        PrinterDeviceCompletionProc
  2467.  
  2468.     Input Parameters:    
  2469.         pb                refCon tells which state we're completing
  2470.  
  2471.     Output Parameters:
  2472.         <none>
  2473.         
  2474.     Description:
  2475.         Complete asynch transactions initiated by PrinterDeviceInitiateTransaction.
  2476.  
  2477.  
  2478.  
  2479.  
  2480.  
  2481.  
  2482.  
  2483.  
  2484.  
  2485.  
  2486. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2487.  
  2488. static void 
  2489. PrinterDeviceCompletionProc(USBPB *pb)
  2490. {
  2491. Str255        tempstr1,tempstr2;
  2492. register     struct usbPrinterPBStruct *pPrinterPB;
  2493. OSStatus    err;
  2494. UInt32        i = 0;
  2495.     
  2496.     
  2497.     pPrinterPB = (struct usbPrinterPBStruct *)(pb);
  2498.  
  2499.     pPrinterPB->transDepth--; 
  2500.     if ((pPrinterPB->transDepth < 0) || (pPrinterPB->transDepth > 1))
  2501.     {
  2502.         USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName "CompletionProc Illegal Transaction Depth", pPrinterPB->transDepth );
  2503.     }
  2504.  
  2505.     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, StateStr(pPrinterPB->pb.usbRefcon, kPString) , pPrinterPB->pb.usbStatus );
  2506.  
  2507.     pPrinterPB->delayInProgress = false;
  2508.     
  2509.     if ( pPrinterPB->terminating )
  2510.     {
  2511.         //    if we've been hot unplugged
  2512.         //        don't startup any new transactions
  2513.         //     allow PrintDriverFinalize to continue
  2514.         pPrinterPB->pb.usbStatus = kUSBAbortedError;
  2515.         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2516.     }
  2517.     
  2518.  
  2519.     switch( pPrinterPB->pb.usbStatus )
  2520.     {
  2521.         case kUSBPending:
  2522.         case noErr:
  2523.             pPrinterPB->pb.usbRefcon &= ~kRetryTransaction;
  2524.             pPrinterPB->retryCount = kPrinterRetryCount;
  2525.             break;
  2526.             
  2527.         case kUSBLinkErr:
  2528.         case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  2529.         case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  2530.         case kUSBDataToggleErr:                            /*  Pipe stall, Bad data toggle */
  2531.         case kUSBNotRespondingErr:                        /*  Pipe stall, No device, device hung */
  2532.         case kUSBPIDCheckErr:                            /*  Pipe stall, PID CRC error */
  2533.         case kUSBWrongPIDErr:                            /*  Pipe stall, Bad or wrong PID */
  2534.         case kUSBTimedOut:                                /* Transaction timed out. */
  2535.         default:
  2536.         
  2537.             USBClearPipeStallByReference(pPrinterPB->deviceRef);  // we got an error, try to clear any stalls
  2538.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName "    retry", pPrinterPB->pb.usbStatus);
  2539.             
  2540.             // clear out the transaction pending flag
  2541.             pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2542.             pPrinterPB->pb.usbRefcon |= kRetryTransaction;
  2543.             pPrinterPB->retryCount--;
  2544.             if (!pPrinterPB->retryCount)
  2545.             {
  2546.                 USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName "Retry failed", pPrinterPB->pb.usbRefcon & ~kRetryTransaction);
  2547.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2548.             } 
  2549.             else 
  2550.             {
  2551.                 pPrinterPB->pb.usbStatus = noErr;             // let's retry one more time
  2552.             }
  2553.             break;
  2554.             
  2555.         case kUSBNotFound:
  2556.             break;
  2557.             
  2558.         case kUSBAbortedError:                        /* user cancel, or hot unplug */
  2559.             // clear out the transaction pending flag
  2560.             pPrinterPB->pb.usbCompletion = (USBCompletion) NULL;
  2561.             pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2562.             pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2563.             break;
  2564.     }
  2565.  
  2566.     if (pPrinterPB->pb.usbRefcon & kTransactionPending)             
  2567.     {            
  2568.         short    length;
  2569.     
  2570.         //
  2571.         //    advance to the next state
  2572.         //
  2573.         pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2574.         switch(pPrinterPB->pb.usbRefcon)
  2575.         {
  2576.             case kFindInterface_bidirectional:
  2577.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_bidirectional completed", pPrinterPB->pb.usb.cntl.WIndex);
  2578.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2579.                 {
  2580.                     if ((pPrinterPB->pb.usbClassType == kUSBPrintingClass) && 
  2581.                         (pPrinterPB->pb.usbSubclass == kUSBPrinterSubclass) &&
  2582.                         (pPrinterPB->pb.usbProtocol == kUSBPrinterBidirectionalProtocol))
  2583.                     {
  2584.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Found bidirectional interface at alt setting ", pPrinterPB->pb.usbOther);
  2585.                         pPrinterPB->configurationNumber = pPrinterPB->pb.usb.cntl.WValue;
  2586.                         pPrinterPB->alternateSetting = pPrinterPB->pb.usbOther;
  2587.                         pPrinterPB->printerProtocol = kUSBPrinterBidirectionalProtocol;
  2588.                         
  2589.                         // if we started out as a device class driver, then the interface descriptor will be NULL
  2590.                         // this would mean that the device will need to be opened before anything can be done with it
  2591.                         // if the interface descriptor point isn't null, then we started as an interface driver,
  2592.                         // so just skip by the opendevice call
  2593.                         if (pPrinterPB->pInterfaceDescriptor != NULL)
  2594.                         {
  2595.                         // did we find the interface we were looking for?
  2596.                             if (pPrinterPB->interfaceNumber == pPrinterPB->pb.usb.cntl.WIndex)
  2597.                             {
  2598.                                 pPrinterPB->pb.usbRefcon = kSetInterface;
  2599.                             }
  2600.                             else
  2601.                             {
  2602.                                 USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_Bidirectional didn't find the right interface", 0);
  2603.                             }
  2604.                         }
  2605.                         else
  2606.                         {
  2607.                             pPrinterPB->pb.usbRefcon = kOpenDevice;
  2608.                             pPrinterPB->interfaceNumber = pPrinterPB->pb.usb.cntl.WIndex;
  2609.                         }
  2610.                     }
  2611.                 }
  2612.                 else
  2613.                 {
  2614.                     if ( pPrinterPB->pb.usbStatus == kUSBNotFound )
  2615.                     {
  2616.                         USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Bidirectional interface was not found", pPrinterPB->pb.usb.cntl.WIndex);
  2617.                         pPrinterPB->pb.usbRefcon = kFindInterface_unidirectional;
  2618.                         pPrinterPB->pb.usbStatus = noErr;  // must clear error for state machine to continue <USB46>
  2619.                     }
  2620.                     else
  2621.                     {
  2622.                         USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_bidirectional failed", 0);
  2623.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2624.                     }
  2625.                 }
  2626.                 break;
  2627.                 
  2628.             case kFindInterface_unidirectional:
  2629.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_unidirectional completed", pPrinterPB->pb.usb.cntl.WIndex);
  2630.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2631.                 {
  2632.                     if ((pPrinterPB->pb.usbClassType == kUSBPrintingClass) && 
  2633.                         (pPrinterPB->pb.usbSubclass == kUSBPrinterSubclass) &&
  2634.                         (pPrinterPB->pb.usbProtocol == kUSBPrinterUnidirectionalProtocol))
  2635.                     {
  2636.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Found unidirection interface at alt setting ", pPrinterPB->pb.usbOther);
  2637.                         pPrinterPB->pb.usbRefcon = kOpenDevice;
  2638.                         pPrinterPB->configurationNumber = pPrinterPB->pb.usb.cntl.WValue;
  2639.                         pPrinterPB->alternateSetting = pPrinterPB->pb.usbOther;
  2640.                         pPrinterPB->printerProtocol = kUSBPrinterUnidirectionalProtocol;
  2641.                         // if we started out as a device class driver, then the interface descriptor will be NULL
  2642.                         // this would mean that the device will need to be opened before anything can be done with it
  2643.                         // if the interface descriptor point isn't null, then we started as an interface driver,
  2644.                         // so just skip by the opendevice call
  2645.                         if (pPrinterPB->pInterfaceDescriptor)
  2646.                         {
  2647.                             if (pPrinterPB->interfaceNumber == pPrinterPB->pb.usb.cntl.WIndex)
  2648.                             {
  2649.                                 pPrinterPB->pb.usbRefcon = kSetInterface;
  2650.                             }
  2651.                             else
  2652.                             {
  2653.                                 USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_Unidirectional didn't find the right interface", 0);
  2654.                             }
  2655.                         }
  2656.                         else
  2657.                         {
  2658.                             pPrinterPB->pb.usbRefcon = kOpenDevice;
  2659.                             pPrinterPB->interfaceNumber = pPrinterPB->pb.usb.cntl.WIndex;
  2660.                         }
  2661.                     }
  2662.                 }
  2663.                 else
  2664.                 {
  2665.                     if ( pPrinterPB->pb.usbStatus == kUSBNotFound )
  2666.                     {
  2667.                         USBExpertStatusLevel(kNormalStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"Unidirectional interface was not found", pPrinterPB->pb.usb.cntl.WIndex);
  2668.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2669.                     }
  2670.                     else
  2671.                     {
  2672.                         USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindInterface_unidirectional failed", 0);
  2673.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2674.                     }
  2675.                 }
  2676.                 break;
  2677.                 
  2678.             case kOpenDevice:
  2679.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2680.                 {
  2681.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kOpenDevice completed", pPrinterPB->pb.usbStatus);
  2682.                     pPrinterPB->pb.usbRefcon = kNewInterfaceRef;
  2683.                 }
  2684.                 else
  2685.                 {
  2686.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kOpenDevice failed", 0);
  2687.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2688.                 }
  2689.                 break;
  2690.                 
  2691.             case kNewInterfaceRef:
  2692.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kNewInterfaceRef completed", pPrinterPB->pb.usbReference);
  2693.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2694.                 {
  2695.                     pPrinterPB->interfaceRef = pPrinterPB->pb.usbReference;
  2696.                     pPrinterPB->pb.usbRefcon = kSetInterface;
  2697.                 }
  2698.                 else
  2699.                 {
  2700.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kNewInterfaceRef failed", 0);
  2701.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2702.                 }
  2703.                 break;
  2704.             
  2705.             case kSetInterface:
  2706.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kSetInterface completed", 0);
  2707.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2708.                 {
  2709.                     pPrinterPB->pb.usbRefcon = kConfigureInterface;
  2710.                 }
  2711.                 else
  2712.                 {
  2713.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kSetInterface failed", 0);
  2714.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2715.                 }
  2716.                 break;
  2717.             
  2718.             case kConfigureInterface:
  2719.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kConfigureInterface completed, pipes = ", pPrinterPB->pb.usbOther);
  2720.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2721.                 {
  2722.                     pPrinterPB->pipeCount = pPrinterPB->pb.usbOther;
  2723.                     pPrinterPB->pb.usbRefcon = kGetCapabilityString;
  2724.                 }
  2725.                 else
  2726.                 {
  2727.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kConfigureInterface failed", 0);
  2728.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2729.                 }
  2730.                 break;
  2731.             
  2732.             case kGetCapabilityString:
  2733.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetCapabilityString completed", pPrinterPB->pb.usbStatus);
  2734.                 
  2735.                 if ( pPrinterPB->pb.usbActCount >= 2 )
  2736.                 {
  2737.                     length = pPrinterPB->pCapabilityString[1] | (pPrinterPB->pCapabilityString[0] << 8);
  2738.                 }
  2739.                 else
  2740.                 {
  2741.                     length = 0;
  2742.                 }
  2743.     
  2744.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2745.                 {
  2746.                     //
  2747.                     //    In the short term (fall '98) several vendors are planning on shipping 
  2748.                     //        devices with a parallel port and using the Lucent USS-720 USB-to-parallel hardware.
  2749.                     //    Unfortunately this isn't an ideal solution from the USB perspective:
  2750.                     //        users can leave the printer off while the cable responds that there's
  2751.                     //        a printer connected. Then we have no way of using the DEVICE_ID
  2752.                     //        string to tag the printer and register it.
  2753.                     //    To alleviate this situation, we repeatedly poll the USS-720 if the DEVICE_ID
  2754.                     //        string is null. Every few seconds we'll retry this state.
  2755.                     //    At some point the user wants to print and switches on the printer. The class
  2756.                     //    driver then picks up from here and registers the device properly.
  2757.                     //
  2758.                     
  2759.                     if ( pPrinterPB->pb.usbActCount == 0 )
  2760.                         pPrinterPB->pb.usbRefcon = kDelayGetCapability;
  2761.                     else
  2762.                         pPrinterPB->pb.usbRefcon = kFindBulkOutPipe;
  2763.                 }
  2764.                 else
  2765.                 {
  2766.                     if ( pPrinterPB->pb.usbStatus == kUSBOverRunErr )
  2767.                     {
  2768.                         //
  2769.                         //    if we've haven't managed to read the whole capability string
  2770.                         //        we need to allocate memory and read it in by initiating kGetFullCapabilityString
  2771.                         //
  2772.     
  2773.                         if ( length > sizeof(pPrinterPB->capability) && pPrinterPB->pb.usbRefcon == kGetCapabilityString )
  2774.                         {
  2775.                             pPrinterPB->pb.usbRefcon = kAllocateCapabilityMem;
  2776.                             pPrinterPB->pb.usbStatus = noErr;  // must clear error for state machine to continue <USB46>
  2777.                             break;                               // advance to that state <USB46>
  2778.                         }    
  2779.                         
  2780.                 
  2781.                     }
  2782.                     else
  2783.                     {
  2784.                         USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kGetCapabilityString failed", 0);
  2785.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2786.                     }
  2787.                 }
  2788.                 
  2789.                 // write the capability string to the log
  2790.                 if ((pPrinterPB->pb.usbStatus == kUSBOverRunErr)  || (pPrinterPB->pb.usbStatus == noErr))
  2791.                 {
  2792.                     if (length > 2)                     // is there a valid string? (length more than 2 bytes)
  2793.                     {
  2794.                         length -= 2;
  2795.                         if (length > 200)                // cut the string off at 200 characters
  2796.                             length = 200;
  2797.                             
  2798.                         BlockMove( (Ptr)&(pPrinterPB->pCapabilityString[2]), (Ptr)tempstr2, length);
  2799.                         tempstr2[length] = '\0';        // mark the end of the cstring
  2800.                         
  2801.                         sprintf( (char *)tempstr1, (char const *) kCStrPrinterDriverName"1284 Capability String: %s", tempstr2 );
  2802.                         CStrToPStr( (unsigned char *)tempstr2, (char *)tempstr1);    // convert it to a pstring
  2803.                     }
  2804.                     else
  2805.                     {
  2806.                         CStrToPStr( (unsigned char *)tempstr2, (char *) kCStrPrinterDriverName"Capability string is empty!!" );
  2807.                     }
  2808.                     USBExpertStatusLevel(kNormalStatusLevel,  pPrinterPB->deviceRef, tempstr2, length);
  2809.                 }
  2810.                 break;
  2811.                 
  2812.             case kDelayGetCapability:
  2813.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kDelayGetCapability completed", pPrinterPB->pb.usbStatus);
  2814.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2815.                 {
  2816.                     pPrinterPB->pb.usbRefcon = kGetCapabilityString;
  2817.                 }
  2818.                 else
  2819.                 {
  2820.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kDelayGetCapability failed", 0);
  2821.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2822.                 }
  2823.                 break;
  2824.                 
  2825.             case kAllocateCapabilityMem:
  2826.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kAllocateCapabilityMem completed", pPrinterPB->pb.usbStatus);
  2827.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2828.                 {
  2829.                     pPrinterPB->pCapabilityString = pPrinterPB->pb.usbBuffer;
  2830.                     pPrinterPB->pb.usbRefcon = kGetFullCapabilityString;    
  2831.                 }
  2832.                 else
  2833.                 {
  2834.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kAllocateCapabilityMem failed", 0);
  2835.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2836.                 }
  2837.                 break;
  2838.             
  2839.             case kGetFullCapabilityString:
  2840.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetFullCapabilityString completed", pPrinterPB->pb.usbStatus);
  2841.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2842.                 {
  2843.                     pPrinterPB->pb.usbRefcon = kGetInterface;
  2844.                 }
  2845.                 else
  2846.                 {
  2847.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kGetFullCapabilityString failed", 0);
  2848.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2849.                 }
  2850.                 break;
  2851.                 
  2852.             case kGetInterface:
  2853.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetInterface completed", pPrinterPB->pb.usbStatus);
  2854.                 if (( pPrinterPB->pb.usbStatus == noErr ) && (pPrinterPB->whichAltInterface == pPrinterPB->alternateSetting))
  2855.                 {
  2856.                     pPrinterPB->pb.usbRefcon = kFindBulkOutPipe;
  2857.                 }
  2858.                 else
  2859.                 {
  2860.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kGetInterface - wrong interface selected", pPrinterPB->whichAltInterface);
  2861.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2862.                 }
  2863.                 break;
  2864.  
  2865.             case kFindBulkOutPipe:
  2866.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkOutPipe completed", pPrinterPB->pb.usbReference);
  2867.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2868.                 {
  2869.                     pPrinterPB->writePipeRef = pPrinterPB->pb.usbReference;             // remember the ref
  2870.                     pPrinterPB->out = pPrinterPB->pb;                                    // copy the paramblock
  2871.                     pPrinterPB->out.usbCompletion =  (USBCompletion) NULL;                // for finalize
  2872.  
  2873.                     if ( pPrinterPB->printerProtocol == kUSBPrinterBidirectionalProtocol )
  2874.                         pPrinterPB->pb.usbRefcon = kFindBulkInPipe;
  2875.                     else
  2876.                         pPrinterPB->pb.usbRefcon = kTaskTimeRequired;
  2877.                 }
  2878.                 else
  2879.                 {
  2880.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindBulkOutPipe failed", 0);
  2881.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2882.                 }
  2883.                 break;
  2884.                 
  2885.             case kFindBulkInPipe:
  2886.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkInPipe completed", pPrinterPB->pb.usbReference);
  2887.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2888.                 {
  2889.                     pPrinterPB->readPipeRef = pPrinterPB->pb.usbReference;
  2890.                     pPrinterPB->in = pPrinterPB->pb;                                    // copy the paramblock
  2891.                     pPrinterPB->in.usbCompletion =  (USBCompletion) NULL;                // for finalize
  2892.  
  2893.                     pPrinterPB->pb.usbRefcon = kTaskTimeRequired;
  2894.                 }
  2895.                 else
  2896.                 {
  2897.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"kFindBulkInPipe failed", 0);
  2898.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2899.                 }
  2900.                 break;
  2901.                 
  2902.             case kTaskTimeRequired:
  2903.                 USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired completed (now at task time)", pPrinterPB->pb.usbReference);
  2904.             //
  2905.             //    once we know what device we're dealing with
  2906.             //        open the i/o channel(s) to the device
  2907.             //        and enter it in the name registry
  2908.             //
  2909.                 
  2910.                 err = InstallDrivers( pPrinterPB );
  2911.                 if ( err == noErr )
  2912.                 {
  2913.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired - drivers installed", pPrinterPB->pb.usbReference);
  2914.                     err = RegisterDevice( pPrinterPB );
  2915.                     if ( err == noErr )
  2916.                     {
  2917.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired - RegisterDevice successful", pPrinterPB->pb.usbReference);
  2918.                     }
  2919.                     else
  2920.                     {
  2921.                         USBExpertFatalError(pPrinterPB->interfaceRef, err, kPStrPrinterDriverName"kTaskTimeRequired - RegisterDevice failed", 0);
  2922.                     }
  2923.                 }
  2924.                 else
  2925.                 {
  2926.                     USBExpertFatalError(pPrinterPB->interfaceRef, err, kPStrPrinterDriverName"kTaskTimeRequired - InstallDrivers failed", 0);
  2927.                 }
  2928.     
  2929.                 pPrinterPB->pb.usbCompletion = (USBCompletion) NULL;                    // Finalize
  2930.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2931.                 {
  2932.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, "\pPrinter driver now exiting setup, calling suspend", pPrinterPB->interfaceRef );
  2933.                     USBPrintDoSuspendResume(pPrinterPB->interfaceRef); 
  2934.                     pPrinterPB->pb.usbRefcon = kReturnFromDriver;
  2935.                     pPrinterPB->printerConfigured = true;
  2936.                 }
  2937.                 else
  2938.                 {
  2939.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, kPStrPrinterDriverName"RegisterDevice failed", 0);
  2940.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2941.                 }
  2942.                 break;
  2943.                 
  2944.             case kGetCentronicsStatus:
  2945.                 //
  2946.                 //    if InitiateTransaction fell through on it's kTaskTimeRequired case we'll end up here
  2947.                 //
  2948.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2949.                 {
  2950.                     unsigned char text[255];
  2951.                     sprintf( (char *)text, " Centronics Status: 0x%02x", pPrinterPB->centronics.b );
  2952.                     text[0] = CStrLen((char *)text); // c2pstr
  2953.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, text, pb->usbStatus );
  2954.                     
  2955. #if DEBUG
  2956.                     if ( !pPrinterPB->centronics.status.notError )
  2957.                     {
  2958.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"Error at printer", pPrinterPB->pb.usbStatus);
  2959.                     }
  2960.                     if ( pPrinterPB->centronics.status.paperError )
  2961.                     {
  2962.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"Check paper", pPrinterPB->pb.usbStatus);
  2963.                     }
  2964.                     if ( !pPrinterPB->centronics.status.select )
  2965.                     {
  2966.                         USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"printer offline", pPrinterPB->pb.usbStatus);
  2967.                     }
  2968. #endif
  2969.                     pPrinterPB->pb.usbRefcon = kDelayGetCentronicsStatus;
  2970.                 }
  2971.                 else
  2972.                 {
  2973.                     USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetCentronicsStatus - error getting centronics status", pPrinterPB->pb.usbStatus);
  2974.                 }
  2975.                 break;
  2976.                 
  2977.             case kDelayGetCentronicsStatus:
  2978.                 //
  2979.                 //    loop around continually getting status
  2980.                 //
  2981.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2982.                 {
  2983.                     pPrinterPB->pb.usbRefcon = kGetCentronicsStatus;
  2984.                 }
  2985.                 break;
  2986.             case kNilCompletion:
  2987.             default:
  2988.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2989.                     pPrinterPB->pb.usbRefcon = kUndefined | kReturnFromDriver;
  2990.                 break;
  2991.         }
  2992.     }
  2993.     
  2994.     // did the removal notification get called?  If so, don't start another transaction.  Just exit
  2995.    if (!pPrinterPB->terminating)
  2996.     {
  2997.         if (pPrinterPB->pb.usbStatus == noErr )
  2998.         {
  2999.             if (!(pPrinterPB->pb.usbRefcon & kReturnFromDriver))
  3000.                 PrinterDeviceInitiateTransaction(pb);
  3001.         }
  3002.         else if ( pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  3003.         {
  3004.             USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, StateStr(pPrinterPB->pb.usbRefcon, kPString), pPrinterPB->pb.usbRefcon);
  3005.             USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, USBStatusStr(pPrinterPB->pb.usbStatus, kPString), 0);
  3006.         }
  3007.     }
  3008.     else
  3009.     {
  3010.         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3011.     }
  3012.     
  3013.     // If we're exiting the driver, then make certain the completion routine is set to NULL
  3014.     // this lets the driver removal task know that there's nothing pending.
  3015.     if ( pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  3016.     {
  3017.         pPrinterPB->pb.usbCompletion    = (USBCompletion) NULL;
  3018.     }
  3019. }
  3020.  
  3021. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3022.     Name:        PrinterDeviceInitiateTransaction
  3023.  
  3024.     Input Parameters:    
  3025.         pb            USB parameter block
  3026.         
  3027.     Output Parameters:
  3028.         
  3029.     Description:
  3030.         Since USB transactions are asynchronous we use the refCon field
  3031.         in the parameter block to implement the following logic via a state machine.
  3032.  
  3033.         Start out by getting the device configuration descriptor
  3034.         If the device has more than one printing interface
  3035.             If a bidirectional interface exists
  3036.                 select it
  3037.             Else
  3038.                 select the (mandatory) unidirectional interface
  3039.         Get the (mandatory) 1284 capability string
  3040.         Open pipes to the BulkOut (and optional BulkIn) endpoints
  3041.         Install read and write drivers in the unit table
  3042.         Using information from the capability string
  3043.             enter the printer in the MacOS name registry.
  3044.         
  3045.  
  3046.  
  3047.  
  3048.  
  3049.  
  3050.  
  3051. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3052. void
  3053. PrinterDeviceInitiateTransaction(USBPB *pb)
  3054. {
  3055. register struct usbPrinterPBStruct    *pPrinterPB;
  3056. UInt16        length;
  3057. OSStatus    err;
  3058.  
  3059.     pPrinterPB = (struct usbPrinterPBStruct *)(pb);
  3060.     
  3061.     pPrinterPB->transDepth++;
  3062.     if ((pPrinterPB->transDepth < 0) || (pPrinterPB->transDepth > 1))
  3063.     {
  3064.         USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName"InitiateTransaction illegal transaction depth", 0);
  3065.     }
  3066.     IF_DEBUG( USBExpertStatusLevel(5 pPrinterPB->deviceRef, StateStr(pPrinterPB->pb.usbRefcon, kPString), 0) );     
  3067.     
  3068.     pPrinterPB->delayInProgress = false;
  3069.     switch(pPrinterPB->pb.usbRefcon & ~kRetryTransaction)
  3070.     {
  3071.         case kFindInterface_bidirectional:
  3072.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_bidirectional", 0);
  3073.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3074.             
  3075.             pPrinterPB->pb.usbBuffer = 0;
  3076.             pPrinterPB->pb.usbActCount = 0;
  3077.             pPrinterPB->pb.usbReqCount = 0;
  3078.             pPrinterPB->pb.usb.cntl.WIndex = 0;
  3079.             pPrinterPB->pb.usb.cntl.WValue = 0;
  3080.             pPrinterPB->pb.usbClassType = kUSBPrintingClass;
  3081.             pPrinterPB->pb.usbSubclass = kUSBPrinterSubclass;
  3082.             pPrinterPB->pb.usbProtocol = kUSBPrinterBidirectionalProtocol;
  3083.             
  3084.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3085.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3086.             err = USBFindNextInterface(pb);
  3087.             if(immediateError(err))
  3088.             {
  3089.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"kFindInterface_bidirectional - immediate error", err);
  3090.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3091.             }
  3092.             break;
  3093.     
  3094.         case kFindInterface_unidirectional:
  3095.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kFindInterface_unidirectional", 0);
  3096.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3097.             
  3098.             pPrinterPB->pb.usbBuffer = 0;
  3099.             pPrinterPB->pb.usbActCount = 0;
  3100.             pPrinterPB->pb.usbReqCount = 0;
  3101.             pPrinterPB->pb.usb.cntl.WIndex = 0;
  3102.             pPrinterPB->pb.usb.cntl.WValue = 0;
  3103.             pPrinterPB->pb.usbClassType = kUSBPrintingClass;
  3104.             pPrinterPB->pb.usbSubclass = kUSBPrinterSubclass;
  3105.             pPrinterPB->pb.usbProtocol = kUSBPrinterUnidirectionalProtocol;
  3106.             
  3107.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3108.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3109.             err = USBFindNextInterface(pb);
  3110.             if(immediateError(err))
  3111.             {
  3112.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"kFindInterface_unidirectional - immediate error", err);
  3113.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3114.             }
  3115.             break;
  3116.     
  3117.         case kOpenDevice:
  3118.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kOpenDevice", 0);
  3119.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3120.             
  3121.             pPrinterPB->pb.usbBuffer = 0;
  3122.             pPrinterPB->pb.usbActCount = 0;
  3123.             pPrinterPB->pb.usbReqCount = 0;
  3124.             pPrinterPB->pb.usb.cntl.WValue = pPrinterPB->configurationNumber;
  3125.             
  3126.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3127.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3128.             err = USBOpenDevice(pb);
  3129.             if(immediateError(err))
  3130.             {
  3131.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"USBOpenDevice - immediate error", err);
  3132.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3133.             }
  3134.             break;
  3135.             
  3136.         case kNewInterfaceRef:
  3137.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->deviceRef, kPStrPrinterDriverName"kNewInterfaceRef for interface number", pPrinterPB->interfaceNumber);
  3138.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  3139.             
  3140.             pPrinterPB->pb.usbBuffer = 0;
  3141.             pPrinterPB->pb.usbActCount = 0;
  3142.             pPrinterPB->pb.usbReqCount = 0;
  3143.             pPrinterPB->pb.usb.cntl.WIndex = pPrinterPB->interfaceNumber;
  3144.             
  3145.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3146.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3147.             err = USBNewInterfaceRef(pb);
  3148.             if(immediateError(err))
  3149.             {
  3150.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"USBNewInterfaceRef - immediate error", err);
  3151.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3152.             }
  3153.             break;
  3154.             
  3155.  
  3156.         case kSetInterface:
  3157.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kSetInterface to alternate setting", pPrinterPB->alternateSetting);
  3158.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3159.             
  3160.             pPrinterPB->pb.usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBOut, kUSBStandard, kUSBInterface);
  3161.         
  3162.             pPrinterPB->pb.usb.cntl.BRequest = kUSBRqSetInterface;
  3163.             pPrinterPB->pb.usb.cntl.WValue = pPrinterPB->alternateSetting;        // alternate setting
  3164.             pPrinterPB->pb.usb.cntl.WIndex = pPrinterPB->interfaceNumber;        // interface
  3165.         
  3166.             pPrinterPB->pb.usbReqCount = 0;
  3167.             pPrinterPB->pb.usbBuffer = NULL;
  3168.         
  3169.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3170.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3171.             err = USBDeviceRequest(pb);
  3172.             if(immediateError(err))
  3173.             {
  3174.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"kSetInterface - immediate error", err);
  3175.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3176.             }
  3177.             break;
  3178.  
  3179.  
  3180.         case kConfigureInterface:
  3181.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kConfigureInterface for alternate setting", pPrinterPB->alternateSetting);
  3182.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3183.             
  3184.             pPrinterPB->pb.usbBuffer = 0;
  3185.             pPrinterPB->pb.usbActCount = 0;
  3186.             pPrinterPB->pb.usbReqCount = 0;
  3187.             pPrinterPB->pb.usbOther = pPrinterPB->alternateSetting;
  3188.             
  3189.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3190.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3191.             err = USBConfigureInterface(pb);
  3192.             if(immediateError(err))
  3193.             {
  3194.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, kPStrPrinterDriverName"USBConfigureInterface - immediate error)", err);
  3195.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3196.             }
  3197.             break;
  3198.             
  3199.         case kGetCapabilityString:
  3200.             //
  3201.             //    once the interface (and alternate) is assinged
  3202.             //        we can retreive the 1284 capability string to see what kind of printer
  3203.             //        is attached
  3204.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetCapabilityString", 0);
  3205.             pPrinterPB->pCapabilityString = pPrinterPB->capability;
  3206.             
  3207.             GetCapability( pPrinterPB, pPrinterPB->pCapabilityString, sizeof(pPrinterPB->capability) );
  3208.             break;
  3209.             
  3210.         case kDelayGetCapability:
  3211.             //
  3212.             //    USS-720 USB-parallel cable: couldn't get the capability string because the printer is off
  3213.             //        Delay a few seconds and try again.
  3214.             //        Will succeed when the user turns the printer on.
  3215.             //
  3216.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kDelayGetCapability", 0);
  3217.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3218.             
  3219.             pPrinterPB->pb.usbBuffer = 0;
  3220.             pPrinterPB->pb.usbActCount = 0;
  3221.             pPrinterPB->pb.usbReqCount = kUSS720MillisecondDelay;
  3222.             pPrinterPB->pb.usbFlags = kUSBTaskTimeFlag;
  3223.             
  3224.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3225.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3226.             pPrinterPB->delayInProgress = true;
  3227.             err = USBDelay(&pPrinterPB->pb);
  3228.             if(immediateError(err))
  3229.             {
  3230.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kDelayGetCapability - immediate error", 0);
  3231.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3232.             }
  3233.             break;
  3234.             
  3235.         case kAllocateCapabilityMem:
  3236.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kAllocateCapabilityMem", 0);
  3237.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3238.             length = *(UInt16*)(pPrinterPB->capability);
  3239.             pPrinterPB->pb.usbBuffer = 0;
  3240.             pPrinterPB->pb.usbActCount = 0;
  3241.             pPrinterPB->pb.usbReqCount = length;
  3242.             pPrinterPB->pb.usbFlags = 0;
  3243.             
  3244.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3245.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3246.             err = USBAllocMem(&pPrinterPB->pb);
  3247.             if(immediateError(err))
  3248.             {
  3249.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kAllocateCapabilityMem - immediate error", 0);
  3250.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3251.             }
  3252.             break;
  3253.         
  3254.         case kGetFullCapabilityString:
  3255.             //
  3256.             // the capability string was too long to fit in the statically allocated space
  3257.             // need to release this memory when we finalize our driver
  3258.             //
  3259.  
  3260.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kGetFullCapabilityString", 0);
  3261.             length = *(UInt16*)(pPrinterPB->capability);
  3262.             if ( pPrinterPB->pCapabilityString )
  3263.                 GetCapability( pPrinterPB, pPrinterPB->pCapabilityString, length );
  3264.             else
  3265.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, kPStrPrinterDriverName"Can't allocate capability memory", 0);
  3266.             break;
  3267.             
  3268.         case kGetInterface:
  3269.             // failsafe check that we've got the right setup
  3270.             //    it's possible the device didn't respond to our SetInterface
  3271.             GetInterface( &pPrinterPB->pb, &pPrinterPB->whichAltInterface );
  3272.             break;
  3273.  
  3274.         case kFindBulkOutPipe:
  3275.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkOutPipe", 0);
  3276.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3277.             
  3278.             pPrinterPB->pb.usbBuffer = 0;
  3279.             pPrinterPB->pb.usbActCount = 0;
  3280.             pPrinterPB->pb.usbReqCount = 0;
  3281.             pPrinterPB->pb.usbFlags = kUSBOut;
  3282.             pPrinterPB->pb.usbClassType = kUSBBulk;
  3283.             
  3284.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3285.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3286.             err = USBFindNextPipe( &pPrinterPB->pb );
  3287.             if (immediateError(err))
  3288.             {
  3289.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, kPStrPrinterDriverName"kFindBulkOutPipe - immediate error", err);
  3290.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3291.             }
  3292.             break;
  3293.             
  3294.         case kFindBulkInPipe:    
  3295.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kFindBulkInPipe", 0);
  3296.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3297.             
  3298.             pPrinterPB->pb.usbBuffer = 0;
  3299.             pPrinterPB->pb.usbActCount = 0;
  3300.             pPrinterPB->pb.usbReqCount = 0;
  3301.             pPrinterPB->pb.usbFlags = kUSBIn;
  3302.             pPrinterPB->pb.usbClassType = kUSBBulk;
  3303.             
  3304.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3305.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3306.             err = USBFindNextPipe( &pPrinterPB->pb );
  3307.             if (immediateError(err))
  3308.             {
  3309.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, kPStrPrinterDriverName"kFindBulkInPipe - immediate error", err);
  3310.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3311.             }
  3312.             break;
  3313.             
  3314.         case kTaskTimeRequired:
  3315.             USBExpertStatusLevel(kDebugStatusLevel, pPrinterPB->interfaceRef, kPStrPrinterDriverName"kTaskTimeRequired", 0);
  3316.              // to stress test usb bus, fallthrough to kGetCentronicsStatus 
  3317.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3318.             
  3319.             pPrinterPB->pb.usbBuffer = 0;
  3320.             pPrinterPB->pb.usbActCount = 0;
  3321.             pPrinterPB->pb.usbReqCount = kUSBNoDelay;
  3322.             pPrinterPB->pb.usbFlags = kUSBTaskTimeFlag;
  3323.             
  3324.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3325.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3326.             pPrinterPB->delayInProgress = true;
  3327.             err = USBDelay(&pPrinterPB->pb);
  3328.             if(immediateError(err))
  3329.             {
  3330.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kTaskTimeRequired - immediate error", 0);
  3331.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3332.             }
  3333.             break;
  3334.  
  3335.         case kGetCentronicsStatus:
  3336.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3337.  
  3338.             CentronicsStatus( &pPrinterPB->pb,  &pPrinterPB->centronics.b, pPrinterPB->interfaceNumber );
  3339.             
  3340.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3341.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3342.             err = USBDeviceRequest(&pPrinterPB->pb);
  3343.             if(immediateError(err))
  3344.             {
  3345.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kGetCentronicsStatus Immediate error", 0);
  3346.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3347.             }
  3348.             break;
  3349.             
  3350.         case kDelayGetCentronicsStatus:
  3351.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  3352.  
  3353.             pPrinterPB->pb.usbBuffer = 0;
  3354.             pPrinterPB->pb.usbActCount = 0;
  3355.             pPrinterPB->pb.usbReqCount = kUSS720StatusMSDelay;
  3356.             
  3357.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  3358.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  3359.             pPrinterPB->delayInProgress = true;
  3360.             err = USBDelay(&pPrinterPB->pb);
  3361.             if(immediateError(err))
  3362.             {
  3363.                 USBExpertFatalError(pb->usbReference, err, kPStrPrinterDriverName"kDelayGetCentronicsStatus - immediate error", 0);
  3364.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3365.             }
  3366.             break;
  3367.             
  3368.         default:
  3369.             USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, kPStrPrinterDriverName"InitiateTransaction - unknown state", pPrinterPB->pb.usbRefcon);
  3370.             pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  3371.             break;
  3372.     }
  3373.     
  3374.     if (pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  3375.     {
  3376.         pPrinterPB->pb.usbCompletion = (USBCompletion) NULL;
  3377.         pPrinterPB->pb.usbRefcon &= ~kTransactionPending;
  3378.     }
  3379. }
  3380.  
  3381.  
  3382. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3383.     Name:        PrintDriverEntry
  3384.  
  3385.     Input Parameters:    
  3386.         
  3387.     Output Parameters:
  3388.         
  3389.     Description:
  3390.         This is where the system instantiates a USB printing device.
  3391.  
  3392.         We need to install drivers in the MacOS unitTable, and a reference
  3393.         in the name registry.
  3394.         
  3395.         But the information we need to do this is only available after some 
  3396.         USB transactions have completed. So we initiate here a series of asynchronous
  3397.         USB operations to get that information (by calling the first 
  3398.  
  3399.  
  3400.  
  3401.  
  3402.  
  3403. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3404. void 
  3405. PrintDriverEntry(
  3406.     USBDeviceRef                    deviceRef,
  3407.     USBDeviceDescriptorPtr            pDeviceDesc,
  3408.     USBInterfaceDescriptorPtr        pInterfaceDesc,
  3409.     UInt32                            interfaceNumber
  3410.     )
  3411. {
  3412.     static Boolean        beenThereDoneThat = false;
  3413.     OSStatus                err;
  3414.     
  3415.     
  3416.     RoutineDescriptor qw = BUILD_ROUTINE_DESCRIPTOR( uppQueueUSBWriteProcInfo, QueueWrite);
  3417.     RoutineDescriptor qr = BUILD_ROUTINE_DESCRIPTOR( uppQueueUSBReadProcInfo, QueueRead);
  3418.     RoutineDescriptor qa = BUILD_ROUTINE_DESCRIPTOR( uppAbortProcInfo, Abort);
  3419.     RoutineDescriptor qs = BUILD_ROUTINE_DESCRIPTOR( uppControlStatusProcInfo, ControlStatusRequests );
  3420.     
  3421.     if( !beenThereDoneThat)
  3422.     {
  3423.         printerClassRecord.terminating = false;
  3424.         printerClassRecord.printerRegistered = false;
  3425.         beenThereDoneThat = true;
  3426.         
  3427.         //DebugStr("\pIn Printer Driver Entry");
  3428.         USBExpertStatusLevel(kNormalStatusLevel, deviceRef, kPStrPrinterDriverName"Starting USB Printer Driver", 0);
  3429.         
  3430.         printerClassRecord.deviceDescriptor = *pDeviceDesc;    /* keep a copy of the device descriptor */
  3431.         printerClassRecord.pInterfaceDescriptor = pInterfaceDesc;
  3432.         printerClassRecord.interfaceNumber = interfaceNumber;
  3433.         
  3434.         printerClassRecord.deviceRef = deviceRef;
  3435.         printerClassRecord.interfaceRef = deviceRef;
  3436.         
  3437.         printerClassRecord.transDepth = 0;            /* init Delay Callback Depth */
  3438.     
  3439.         printerClassRecord.inRefNum =  -1;            /* initially no DRVRs added to UnitTable */
  3440.         printerClassRecord.outRefNum =  -1;    
  3441.         err = LoadResources( &printerClassRecord );
  3442.         if ( err != noErr )  
  3443.             USBExpertFatalError( deviceRef, err, kPStrPrinterDriverName"LoadResources failed", 0);
  3444.         //
  3445.         //    routines to write and read to the device must be called by 68K DRVR
  3446.         //        so we use mixed-mode manager to dispatch between PPC and 68K
  3447.         //
  3448.         printerClassRecord.qwrite = (QueueUSBWriteUPP) &printerClassRecord.qwriteRD;
  3449.         printerClassRecord.qwriteRD = qw;
  3450.     
  3451.         printerClassRecord.qread = (QueueUSBReadUPP) &printerClassRecord.qreadRD;
  3452.         printerClassRecord.qreadRD = qr;    
  3453.         
  3454.         printerClassRecord.qstatus = (ControlStatusUPP) &printerClassRecord.qstatusRD;
  3455.         printerClassRecord.qstatusRD = qs;
  3456.  
  3457.         printerClassRecord.qabort = (AbortUPP) &printerClassRecord.qabortRD;
  3458.         printerClassRecord.qabortRD = qa;
  3459.  
  3460.         printerClassRecord.r = (QueueUSBReadUPP) QueueRead;
  3461.         printerClassRecord.w = (QueueUSBWriteUPP) QueueWrite;
  3462.         printerClassRecord.s = (ControlStatusUPP) ControlStatusRequests;
  3463.         printerClassRecord.a = (AbortUPP) Abort;
  3464.    
  3465.         SetNullUSBParamBlock( deviceRef, &printerClassRecord.pb );
  3466.         SetNullUSBParamBlock( 0, &printerClassRecord.in );        // fill in pipe ref later
  3467.         SetNullUSBParamBlock( 0, &printerClassRecord.out );    // fill in pipe ref later
  3468.         
  3469.         CStrCopy((char *)printerClassRecord.name, "");
  3470.         CStrCopy((char *)printerClassRecord.model, "");
  3471.  
  3472. #if DOUBLE_BUFFER
  3473.         //
  3474.         // Assume 1. TRANSFER_SIZE is a power of 2
  3475.         //    Assume 2. malignedBuffer is allocated to be 3*TRANSFER_SIZE
  3476.         //
  3477.         printerClassRecord.pageWriteAlignedBufferSize = TRANSFER_SIZE;                            // should get this from VM
  3478.         printerClassRecord.pageWriteAlignedBuffer = printerClassRecord.malignedBuffer;
  3479.  
  3480.         // align it below the buffer, then bring it into the range of the buffer
  3481.         *((UInt32 *) &printerClassRecord.pageWriteAlignedBuffer) &= ~(printerClassRecord.pageWriteAlignedBufferSize - 1);    //assumption1
  3482.         *((UInt32 *) &printerClassRecord.pageWriteAlignedBuffer) += printerClassRecord.pageWriteAlignedBufferSize;            //assumption2
  3483.  
  3484.         printerClassRecord.pageReadAlignedBufferSize = TRANSFER_SIZE;
  3485.         printerClassRecord.pageReadAlignedBuffer = printerClassRecord.pageWriteAlignedBuffer + TRANSFER_SIZE;
  3486.         
  3487. #endif
  3488.         printerClassRecord.printerConfigured = false;
  3489.     
  3490.         //
  3491.         //    Just to be thorough, lets hold our paramter blocks so that we won't page them at
  3492.         //        interrupt time. (We should be in the System heap and automatically held.)
  3493.         //
  3494.         HoldMemory( &printerClassRecord, sizeof(struct usbPrinterPBStruct) );
  3495.  
  3496.         CheckUSBVersion();
  3497.         
  3498.         //
  3499.         // Start out at first state
  3500.         //
  3501.         printerClassRecord.pCapabilityString = printerClassRecord.capability;
  3502.         printerClassRecord.pb.usbRefcon = kFindInterface_bidirectional;
  3503.         
  3504.         // don't start if we received a removal notification just as we're starting up
  3505.         if (printerClassRecord.terminating)
  3506.         {
  3507.             printerClassRecord.pb.usbCompletion    = (USBCompletion) NULL;
  3508.         }
  3509.         else
  3510.         {
  3511.             PrinterDeviceInitiateTransaction(&printerClassRecord.pb);
  3512.         }
  3513.     }
  3514. }
  3515.  
  3516. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3517.     Name:        PrinterRemovalNotification
  3518.  
  3519.     Input Parameters:    
  3520.         
  3521.     Output Parameters:
  3522.         
  3523.     Description:
  3524.         release any allocated storage
  3525.         remove DRVRs from the UnitTable
  3526.  
  3527.         One small complication happens when the USS-720 cable is used. It's possible
  3528.         that the user has the device plugged in, but the printer wasn't powered on.
  3529.         In this case, our state machine is still cycling between the states 
  3530.         kDelayGetCapability and kGetCapabilityString. If we terminate before the delay
  3531.         returns we'll crash the system. We monitor terminating to handle this
  3532.         
  3533.  
  3534.  
  3535.  
  3536.  
  3537.  
  3538.  
  3539.  
  3540.  
  3541.  
  3542. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3543. OSStatus
  3544. PrinterRemovalNotification( void )
  3545. {
  3546. static    Boolean    logfileclosed = false;
  3547. static    Boolean    aborted = false;
  3548. static    Boolean    deregistered = false;
  3549. static    Boolean    readpipeaborted = false;
  3550. static    Boolean    writepipeaborted = false;
  3551. static    Boolean    timedout = false;
  3552. OSStatus            result = noErr;
  3553. static unsigned long    tc = 0;
  3554.     //
  3555.     //    notify state machine not to continue
  3556.     //
  3557.     printerClassRecord.terminating = true;
  3558.     
  3559.     USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Driver removal notification received", 0);
  3560.     if (!logfileclosed)
  3561.     {
  3562.         USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Closing printer log file", 0);
  3563.         LOGGING( fclose( logfile ) );
  3564.         logfileclosed = true;
  3565.         return (OSStatus) kUSBDeviceBusy;
  3566.     }
  3567.     
  3568.     // per the Mac OS USB DDK API Ref 
  3569.     // "If the device associated with this call [USBDelay] is unplugged and its driver removed while
  3570.     //  this function call is pending, the function will not complete."
  3571.     // therefore don't hang around if a delay is in progress
  3572.     if (( printerClassRecord.pb.usbCompletion != (USBCompletion) NULL ) && (!printerClassRecord.delayInProgress))
  3573.     {
  3574.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Waiting for configuration to complete", printerClassRecord.pb.usbRefcon);
  3575.         return (OSStatus) kUSBDeviceBusy;
  3576.     }
  3577.     
  3578.     // Abort any outstanding write requests
  3579.     if (( printerClassRecord.out.usbCompletion != (USBCompletion) NULL ) && (!writepipeaborted))
  3580.     {
  3581.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Abort write pipe", printerClassRecord.writePipeRef);
  3582.         USBAbortPipeByReference( printerClassRecord.writePipeRef );
  3583.         writepipeaborted = true;
  3584.         return (OSStatus) kUSBDeviceBusy;
  3585.     }
  3586.     
  3587.     // Abort any outstanding read requests
  3588.     if (( printerClassRecord.in.usbCompletion != (USBCompletion) NULL ) && (!readpipeaborted))
  3589.     {
  3590.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Abort read pipe", printerClassRecord.readPipeRef );
  3591.         USBAbortPipeByReference( printerClassRecord.readPipeRef );
  3592.         readpipeaborted = true;
  3593.         return (OSStatus) kUSBDeviceBusy;
  3594.     }
  3595.     
  3596.     // Abort any outstanding transactions
  3597.     if (!aborted)
  3598.     {
  3599.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Call Abort()", 0);
  3600.         Abort( 0, &printerClassRecord );
  3601.         aborted = true;
  3602.         return (OSStatus) kUSBDeviceBusy;
  3603.     }
  3604.  
  3605.     // wait up to ten seconds for the read & write routines to complete.  When they do, the completion procptrs will be NULL'd
  3606.     if (tc == 0)
  3607.         tc = TickCount() + 10*60;
  3608.         
  3609.     if ( TickCount() >= tc )
  3610.         timedout = true;
  3611.         
  3612.     if (( TickCount() < tc ) &&
  3613.          (( printerClassRecord.out.usbCompletion != (USBCompletion) NULL) ||
  3614.           ( printerClassRecord.in.usbCompletion != (USBCompletion) NULL )))
  3615.     {
  3616.         return (OSStatus) kUSBDeviceBusy;
  3617.     }
  3618.     
  3619.     // Put the appropriate timeout message in the log
  3620.     if ( timedout )
  3621.     {
  3622.         USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"took longer than 10 seconds for read/write pipes to complete", 0);
  3623.     }
  3624.     else
  3625.     {
  3626.         USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Pipes closed normally", 0);
  3627.     }
  3628.     
  3629.     if (( printerClassRecord.out.usbCompletion != (USBCompletion) NULL) ||
  3630.           ( printerClassRecord.in.usbCompletion != (USBCompletion) NULL ))
  3631.     {
  3632.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Completion procs are not nil!!", 0);
  3633.     }
  3634.     
  3635.     // if the printer was never registered, then don't try to deregister it
  3636.     if (!(printerClassRecord.printerRegistered))
  3637.         deregistered = true;
  3638.         
  3639.     if (!deregistered)    
  3640.     {
  3641.         //
  3642.         //    remove printer from the name registry
  3643.         //
  3644.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Removed printer entry from nameregistry", 0);
  3645.         DeregisterDevice( &printerClassRecord );
  3646.         deregistered = true;
  3647.         return (OSStatus) kUSBDeviceBusy;
  3648.     }
  3649.  
  3650.     //
  3651.     //    release any allocated storage
  3652.     //
  3653.     if ( printerClassRecord.pCapabilityString != printerClassRecord.capability )
  3654.     {
  3655.         USBExpertStatusLevel(kDebugStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Deallocated capability string memory", 0);
  3656.         printerClassRecord.pb.usbReference = printerClassRecord.deviceRef;             
  3657.         printerClassRecord.pb.usbFlags = 0;             
  3658.         printerClassRecord.pb.usbRefcon = kDeallocateCapbilityString;             
  3659.         printerClassRecord.pb.usbBuffer = printerClassRecord.pCapabilityString;        
  3660.         printerClassRecord.pb.usbCompletion = (USBCompletion)kUSBNoCallBack;
  3661.         printerClassRecord.delayInProgress = true;        // this prevents the control pipe completion procptr from being checked
  3662.         USBDeallocMem(&printerClassRecord.pb);
  3663.         
  3664.         printerClassRecord.pCapabilityString = printerClassRecord.capability;
  3665.         return (OSStatus) kUSBDeviceBusy;
  3666.     }
  3667.  
  3668.     //
  3669.     //    don't need to hang on to param blocks after we've gone away
  3670.     //
  3671.     UnholdMemory( &printerClassRecord, sizeof(struct usbPrinterPBStruct) );
  3672.  
  3673.     USBExpertStatusLevel(kNormalStatusLevel, printerClassRecord.deviceRef, kPStrPrinterDriverName"Ready for removal", 0);
  3674.     return kUSBNoErr;
  3675. }
  3676.  
  3677. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3678.     Name:        CFMInitialization
  3679.  
  3680.     Input Parameters:    
  3681.         initBlock
  3682.         
  3683.     Output Parameters:
  3684.         printerClassDriverFileSpec        set global
  3685.         
  3686.     Description:
  3687.         We use the code fragment initialization to get our filespec which 
  3688.         LoadResources will use to open our resource fork.
  3689.         
  3690.         A peculiarity of the USB 1.0 implementation is that does not lock the
  3691.         driver into physical memory. As a result a driver which does not call
  3692.         SetDriverClosureMemory on it's fragment will likely be paged in during
  3693.         interrupt time and a double bus-fault will occur. The solution for this
  3694.         is to have the USB Expert call SetDriverClosureMemory in a future release
  3695.         of the USB stack. In the meantime, we call it on ourselves to lock us into
  3696.         physical memory. When the USB stack is revved, one call to SetDriverClosureMemory
  3697.         (either this one or the Expert's) will be treated as a NOP.
  3698.  
  3699.  
  3700.  
  3701.  
  3702. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3703. OSErr
  3704. CFMInitialization( CFragInitBlock *initBlock )
  3705. {
  3706.     //
  3707.     //    get a reference to our file so that we can open up the resource fork later on
  3708.     //
  3709.     if ( CFragHasFileLocation( initBlock->fragLocator.where ) )
  3710.         printerClassDriverFileSpec = *(initBlock->fragLocator.u.onDisk.fileSpec);
  3711.  
  3712.     return noErr;
  3713.  
  3714. }
  3715.  
  3716. // eof
  3717.